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/states/cron.py
env_absent
python
def env_absent(name, user='root'): ''' Verifies that the specified environment variable is absent from the crontab for the specified user name The name of the environment variable to remove from the user crontab user The name of the user whose crontab needs to be modified, defaults to the root user ''' name = name.strip() ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} if __opts__['test']: status = _check_cron_env(user, name) ret['result'] = None if status == 'absent': ret['result'] = True ret['comment'] = 'Cron env {0} is absent'.format(name) elif status == 'present' or status == 'update': ret['comment'] = 'Cron env {0} is set to be removed'.format(name) return ret data = __salt__['cron.rm_env'](user, name) if data == 'absent': ret['comment'] = "Cron env {0} already absent".format(name) return ret if data == 'removed': ret['comment'] = ("Cron env {0} removed from {1}'s crontab" .format(name, user)) ret['changes'] = {user: name} return ret ret['comment'] = ("Cron env {0} for user {1} failed to commit with error {2}" .format(name, user, data)) ret['result'] = False return ret
Verifies that the specified environment variable is absent from the crontab for the specified user name The name of the environment variable to remove from the user crontab user The name of the user whose crontab needs to be modified, defaults to the root user
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L725-L767
[ "def _check_cron_env(user,\n name,\n value=None):\n '''\n Return the environment changes\n '''\n if value is None:\n value = \"\" # Matching value set in salt.modules.cron._render_tab\n lst = __salt__['cron.list_tab'](user)\n for env in lst['env']:\n if name == env['name']:\n if value != env['value']:\n return 'update'\n return 'present'\n return 'absent'\n" ]
# -*- coding: utf-8 -*- ''' Management of cron, the Unix command scheduler ============================================== Cron declarations require a number of parameters. The following are the parameters used by Salt to define the various timing values for a cron job: * ``minute`` * ``hour`` * ``daymonth`` * ``month`` * ``dayweek`` (0 to 6 are Sunday through Saturday, 7 can also be used for Sunday) .. warning:: Any timing arguments not specified take a value of ``*``. This means that setting ``hour`` to ``5``, while not defining the ``minute`` param, will result in Salt adding a job that will execute every minute between 5 and 6 A.M.! Additionally, the default user for these states is ``root``. Therefore, if the cron job is for another user, it is necessary to specify that user with the ``user`` parameter. A long time ago (before 2014.2), when making changes to an existing cron job, the name declaration is the parameter used to uniquely identify the job, so if an existing cron that looks like this: .. code-block:: yaml date > /tmp/crontest: cron.present: - user: root - minute: 5 Is changed to this: .. code-block:: yaml date > /tmp/crontest: cron.present: - user: root - minute: 7 - hour: 2 Then the existing cron will be updated, but if the cron command is changed, then a new cron job will be added to the user's crontab. The current behavior is still relying on that mechanism, but you can also specify an identifier to identify your crontabs: .. code-block:: yaml date > /tmp/crontest: cron.present: - identifier: SUPERCRON - user: root - minute: 7 - hour: 2 .. versionadded:: 2014.1.2 And, some months later, you modify it: .. code-block:: yaml superscript > /tmp/crontest: cron.present: - identifier: SUPERCRON - user: root - minute: 3 - hour: 4 .. versionadded:: 2014.1.2 The old **date > /tmp/crontest** will be replaced by **superscript > /tmp/crontest**. Additionally, Salt also supports running a cron every ``x minutes`` very similarly to the Unix convention of using ``*/5`` to have a job run every five minutes. In Salt, this looks like: .. code-block:: yaml date > /tmp/crontest: cron.present: - user: root - minute: '*/5' The job will now run every 5 minutes. Additionally, the temporal parameters (minute, hour, etc.) can be randomized by using ``random`` instead of using a specific value. For example, by using the ``random`` keyword in the ``minute`` parameter of a cron state, the same cron job can be pushed to hundreds or thousands of hosts, and they would each use a randomly-generated minute. This can be helpful when the cron job accesses a network resource, and it is not desirable for all hosts to run the job concurrently. .. code-block:: yaml /path/to/cron/script: cron.present: - user: root - minute: random - hour: 2 .. versionadded:: 0.16.0 Since Salt assumes a value of ``*`` for unspecified temporal parameters, adding a parameter to the state and setting it to ``random`` will change that value from ``*`` to a randomized numeric value. However, if that field in the cron entry on the minion already contains a numeric value, then using the ``random`` keyword will not modify it. Added the opportunity to set a job with a special keyword like '@reboot' or '@hourly'. Quotes must be used, otherwise PyYAML will strip the '@' sign. .. code-block:: yaml /path/to/cron/script: cron.present: - user: root - special: '@hourly' The script will be executed every reboot if cron daemon support this option. .. code-block:: yaml /path/to/cron/otherscript: cron.absent: - user: root - special: '@daily' This counter part definition will ensure than a job with a special keyword is not set. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os # Import salt libs import salt.utils.files from salt.modules.cron import ( _needs_change, _cron_matched ) from salt.ext import six def __virtual__(): if 'cron.list_tab' in __salt__: return True else: return (False, 'cron module could not be loaded') def _check_cron(user, cmd, minute=None, hour=None, daymonth=None, month=None, dayweek=None, comment=None, commented=None, identifier=None, special=None): ''' Return the changes ''' if minute is not None: minute = six.text_type(minute).lower() if hour is not None: hour = six.text_type(hour).lower() if daymonth is not None: daymonth = six.text_type(daymonth).lower() if month is not None: month = six.text_type(month).lower() if dayweek is not None: dayweek = six.text_type(dayweek).lower() if identifier is not None: identifier = six.text_type(identifier) if commented is not None: commented = commented is True if cmd is not None: cmd = six.text_type(cmd) lst = __salt__['cron.list_tab'](user) if special is None: for cron in lst['crons']: if _cron_matched(cron, cmd, identifier): if any([_needs_change(x, y) for x, y in ((cron['minute'], minute), (cron['hour'], hour), (cron['daymonth'], daymonth), (cron['month'], month), (cron['dayweek'], dayweek), (cron['identifier'], identifier), (cron['cmd'], cmd), (cron['comment'], comment), (cron['commented'], commented))]): return 'update' return 'present' else: for cron in lst['special']: if _cron_matched(cron, cmd, identifier): if any([_needs_change(x, y) for x, y in ((cron['spec'], special), (cron['identifier'], identifier), (cron['cmd'], cmd), (cron['comment'], comment), (cron['commented'], commented))]): return 'update' return 'present' return 'absent' def _check_cron_env(user, name, value=None): ''' Return the environment changes ''' if value is None: value = "" # Matching value set in salt.modules.cron._render_tab lst = __salt__['cron.list_tab'](user) for env in lst['env']: if name == env['name']: if value != env['value']: return 'update' return 'present' return 'absent' def _get_cron_info(): ''' Returns the proper group owner and path to the cron directory ''' owner = 'root' if __grains__['os'] == 'FreeBSD': group = 'wheel' crontab_dir = '/var/cron/tabs' elif __grains__['os'] == 'OpenBSD': group = 'crontab' crontab_dir = '/var/cron/tabs' elif __grains__['os_family'] == 'Solaris': group = 'root' crontab_dir = '/var/spool/cron/crontabs' elif __grains__['os'] == 'MacOS': group = 'wheel' crontab_dir = '/usr/lib/cron/tabs' else: group = 'root' crontab_dir = '/var/spool/cron' return owner, group, crontab_dir def present(name, user='root', minute='*', hour='*', daymonth='*', month='*', dayweek='*', comment=None, commented=False, identifier=False, special=None): ''' Verifies that the specified cron job is present for the specified user. It is recommended to use `identifier`. Otherwise the cron job is installed twice if you change the name. For more advanced information about what exactly can be set in the cron timing parameters, check your cron system's documentation. Most Unix-like systems' cron documentation can be found via the crontab man page: ``man 5 crontab``. name The command that should be executed by the cron job. user The name of the user whose crontab needs to be modified, defaults to the root user minute The information to be set into the minute section, this can be any string supported by your cron system's the minute field. Default is ``*`` hour The information to be set in the hour section. Default is ``*`` daymonth The information to be set in the day of month section. Default is ``*`` month The information to be set in the month section. Default is ``*`` dayweek The information to be set in the day of week section. Default is ``*`` comment User comment to be added on line previous the cron job commented The cron job is set commented (prefixed with ``#DISABLED#``). Defaults to False. .. versionadded:: 2016.3.0 identifier Custom-defined identifier for tracking the cron line for future crontab edits. This defaults to the state name special A special keyword to specify periodicity (eg. @reboot, @hourly...). Quotes must be used, otherwise PyYAML will strip the '@' sign. .. versionadded:: 2016.3.0 ''' name = name.strip() if identifier is False: identifier = name ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if __opts__['test']: status = _check_cron(user, cmd=name, minute=minute, hour=hour, daymonth=daymonth, month=month, dayweek=dayweek, comment=comment, commented=commented, identifier=identifier, special=special) ret['result'] = None if status == 'absent': ret['comment'] = 'Cron {0} is set to be added'.format(name) elif status == 'present': ret['result'] = True ret['comment'] = 'Cron {0} already present'.format(name) elif status == 'update': ret['comment'] = 'Cron {0} is set to be updated'.format(name) return ret if special is None: data = __salt__['cron.set_job'](user=user, minute=minute, hour=hour, daymonth=daymonth, month=month, dayweek=dayweek, cmd=name, comment=comment, commented=commented, identifier=identifier) else: data = __salt__['cron.set_special'](user=user, special=special, cmd=name, comment=comment, commented=commented, identifier=identifier) if data == 'present': ret['comment'] = 'Cron {0} already present'.format(name) return ret if data == 'new': ret['comment'] = 'Cron {0} added to {1}\'s crontab'.format(name, user) ret['changes'] = {user: name} return ret if data == 'updated': ret['comment'] = 'Cron {0} updated'.format(name) ret['changes'] = {user: name} return ret ret['comment'] = ('Cron {0} for user {1} failed to commit with error \n{2}' .format(name, user, data)) ret['result'] = False return ret def absent(name, user='root', identifier=False, special=None, **kwargs): ''' Verifies that the specified cron job is absent for the specified user; only the name is matched when removing a cron job. name The command that should be absent in the user crontab. user The name of the user whose crontab needs to be modified, defaults to the root user identifier Custom-defined identifier for tracking the cron line for future crontab edits. This defaults to the state name special The special keyword used in the job (eg. @reboot, @hourly...). Quotes must be used, otherwise PyYAML will strip the '@' sign. ''' # NOTE: The keyword arguments in **kwargs are ignored in this state, but # cannot be removed from the function definition, otherwise the use # of unsupported arguments will result in a traceback. name = name.strip() if identifier is False: identifier = name ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} if __opts__['test']: status = _check_cron(user, name, identifier=identifier) ret['result'] = None if status == 'absent': ret['result'] = True ret['comment'] = 'Cron {0} is absent'.format(name) elif status == 'present' or status == 'update': ret['comment'] = 'Cron {0} is set to be removed'.format(name) return ret if special is None: data = __salt__['cron.rm_job'](user, name, identifier=identifier) else: data = __salt__['cron.rm_special'](user, name, special=special, identifier=identifier) if data == 'absent': ret['comment'] = "Cron {0} already absent".format(name) return ret if data == 'removed': ret['comment'] = ("Cron {0} removed from {1}'s crontab" .format(name, user)) ret['changes'] = {user: name} return ret ret['comment'] = ("Cron {0} for user {1} failed to commit with error {2}" .format(name, user, data)) ret['result'] = False return ret def file(name, source_hash='', source_hash_name=None, user='root', template=None, context=None, replace=True, defaults=None, backup='', **kwargs): ''' Provides file.managed-like functionality (templating, etc.) for a pre-made crontab file, to be assigned to a given user. name The source file to be used as the crontab. This source file can be hosted on either the salt master server, or on an HTTP or FTP server. For files hosted on the salt file server, if the file is located on the master in the directory named spam, and is called eggs, the source string is ``salt://spam/eggs`` If the file is hosted on a HTTP or FTP server then the source_hash argument is also required source_hash This can be either a file which contains a source hash string for the source, or a source hash string. The source hash string is the hash algorithm followed by the hash of the file: ``md5=e138491e9d5b97023cea823fe17bac22`` source_hash_name When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the filename/URI associated with that hash. By default, Salt will look for the filename being managed. When managing a file at path ``/tmp/foo.txt``, then the following line in a hash file would match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 foo.txt However, sometimes a hash file will include multiple similar paths: .. code-block:: text 37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt 73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt In cases like this, Salt may match the incorrect hash. This argument can be used to tell Salt which filename to match, to ensure that the correct hash is identified. For example: .. code-block:: yaml foo_crontab: cron.file: - name: https://mydomain.tld/dir2/foo.txt - source_hash: https://mydomain.tld/hashes - source_hash_name: ./dir2/foo.txt .. note:: This argument must contain the full filename entry from the checksum file, as this argument is meant to disambiguate matches for multiple files that have the same basename. So, in the example above, simply using ``foo.txt`` would not match. .. versionadded:: 2016.3.5 user The user to whom the crontab should be assigned. This defaults to root. template If this setting is applied then the named templating engine will be used to render the downloaded file. Currently, jinja and mako are supported. context Overrides default context variables passed to the template. replace If the crontab should be replaced, if False then this command will be ignored if a crontab exists for the specified user. Default is True. defaults Default context passed to the template. backup Overrides the default backup mode for the user's crontab. ''' # Initial set up mode = '0600' try: group = __salt__['user.info'](user)['groups'][0] except Exception: ret = {'changes': {}, 'comment': "Could not identify group for user {0}".format(user), 'name': name, 'result': False} return ret cron_path = salt.utils.files.mkstemp() with salt.utils.files.fopen(cron_path, 'w+') as fp_: raw_cron = __salt__['cron.raw_cron'](user) if not raw_cron.endswith('\n'): raw_cron = "{0}\n".format(raw_cron) fp_.write(salt.utils.stringutils.to_str(raw_cron)) ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Avoid variable naming confusion in below module calls, since ID # declaration for this state will be a source URI. source = name if not replace and os.stat(cron_path).st_size > 0: ret['comment'] = 'User {0} already has a crontab. No changes ' \ 'made'.format(user) os.unlink(cron_path) return ret if __opts__['test']: fcm = __salt__['file.check_managed'](name=cron_path, source=source, source_hash=source_hash, source_hash_name=source_hash_name, user=user, group=group, mode=mode, attrs=[], # no special attrs for cron template=template, context=context, defaults=defaults, saltenv=__env__, **kwargs ) ret['result'], ret['comment'] = fcm os.unlink(cron_path) return ret # If the source is a list then find which file exists source, source_hash = __salt__['file.source_list'](source, source_hash, __env__) # Gather the source file from the server try: sfn, source_sum, comment = __salt__['file.get_managed']( name=cron_path, template=template, source=source, source_hash=source_hash, source_hash_name=source_hash_name, user=user, group=group, mode=mode, attrs=[], saltenv=__env__, context=context, defaults=defaults, skip_verify=False, # skip_verify **kwargs ) except Exception as exc: ret['result'] = False ret['changes'] = {} ret['comment'] = 'Unable to manage file: {0}'.format(exc) return ret if comment: ret['comment'] = comment ret['result'] = False os.unlink(cron_path) return ret try: ret = __salt__['file.manage_file']( name=cron_path, sfn=sfn, ret=ret, source=source, source_sum=source_sum, user=user, group=group, mode=mode, attrs=[], saltenv=__env__, backup=backup ) except Exception as exc: ret['result'] = False ret['changes'] = {} ret['comment'] = 'Unable to manage file: {0}'.format(exc) return ret cron_ret = None if "diff" in ret['changes']: cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path) # Check cmd return code and show success or failure if cron_ret['retcode'] == 0: ret['comment'] = 'Crontab for user {0} was updated'.format(user) ret['result'] = True ret['changes'] = ret['changes'] else: ret['comment'] = 'Unable to update user {0} crontab {1}.' \ ' Error: {2}'.format(user, cron_path, cron_ret['stderr']) ret['result'] = False ret['changes'] = {} elif ret['result']: ret['comment'] = 'Crontab for user {0} is in the correct ' \ 'state'.format(user) ret['changes'] = {} os.unlink(cron_path) return ret def env_present(name, value=None, user='root'): ''' Verifies that the specified environment variable is present in the crontab for the specified user. name The name of the environment variable to set in the user crontab user The name of the user whose crontab needs to be modified, defaults to the root user value The value to set for the given environment variable ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if __opts__['test']: status = _check_cron_env(user, name, value=value) ret['result'] = None if status == 'absent': ret['comment'] = 'Cron env {0} is set to be added'.format(name) elif status == 'present': ret['result'] = True ret['comment'] = 'Cron env {0} already present'.format(name) elif status == 'update': ret['comment'] = 'Cron env {0} is set to be updated'.format(name) return ret data = __salt__['cron.set_env'](user, name, value=value) if data == 'present': ret['comment'] = 'Cron env {0} already present'.format(name) return ret if data == 'new': ret['comment'] = 'Cron env {0} added to {1}\'s crontab'.format(name, user) ret['changes'] = {user: name} return ret if data == 'updated': ret['comment'] = 'Cron env {0} updated'.format(name) ret['changes'] = {user: name} return ret ret['comment'] = ('Cron env {0} for user {1} failed to commit with error \n{2}' .format(name, user, data)) ret['result'] = False return ret
saltstack/salt
salt/output/highstate.py
output
python
def output(data, **kwargs): # pylint: disable=unused-argument ''' The HighState Outputter is only meant to be used with the state.highstate function, or a function that returns highstate return data. ''' if len(data.keys()) == 1: # account for nested orchs via saltutil.runner if 'return' in data: data = data['return'] # account for envelope data if being passed lookup_jid ret if isinstance(data, dict): _data = next(iter(data.values())) if 'jid' in _data and 'fun' in _data: data = _data['return'] # output() is recursive, if we aren't passed a dict just return it if isinstance(data, int) or isinstance(data, six.string_types): return data # Discard retcode in dictionary as present in orchestrate data local_masters = [key for key in data.keys() if key.endswith('_master')] orchestrator_output = 'retcode' in data.keys() and len(local_masters) == 1 if orchestrator_output: del data['retcode'] # If additional information is passed through via the "data" dictionary to # the highstate outputter, such as "outputter" or "retcode", discard it. # We only want the state data that was passed through, if it is wrapped up # in the "data" key, as the orchestrate runner does. See Issue #31330, # pull request #27838, and pull request #27175 for more information. if 'data' in data: data = data.pop('data') indent_level = kwargs.get('indent_level', 1) ret = [ _format_host(host, hostdata, indent_level=indent_level)[0] for host, hostdata in six.iteritems(data) ] if ret: return "\n".join(ret) log.error( 'Data passed to highstate outputter is not a valid highstate return: %s', data ) # We should not reach here, but if we do return empty string return ''
The HighState Outputter is only meant to be used with the state.highstate function, or a function that returns highstate return data.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/highstate.py#L136-L183
null
# -*- coding: utf-8 -*- ''' Outputter for displaying results of state runs ============================================== The return data from the Highstate command is a standard data structure which is parsed by the highstate outputter to deliver a clean and readable set of information about the HighState run on minions. Two configurations can be set to modify the highstate outputter. These values can be set in the master config to change the output of the ``salt`` command or set in the minion config to change the output of the ``salt-call`` command. state_verbose By default `state_verbose` is set to `True`, setting this to `False` will instruct the highstate outputter to omit displaying anything in green, this means that nothing with a result of True and no changes will not be printed state_output: The highstate outputter has six output modes, ``full``, ``terse``, ``mixed``, ``changes`` and ``filter`` * The default is set to ``full``, which will display many lines of detailed information for each executed chunk. * If ``terse`` is used, then the output is greatly simplified and shown in only one line. * If ``mixed`` is used, then terse output will be used unless a state failed, in which case full output will be used. * If ``changes`` is used, then terse output will be used if there was no error and no changes, otherwise full output will be used. * If ``filter`` is used, then either or both of two different filters can be used: ``exclude`` or ``terse``. * for ``exclude``, state.highstate expects a list of states to be excluded (or ``None``) followed by ``True`` for terse output or ``False`` for regular output. Because of parsing nuances, if only one of these is used, it must still contain a comma. For instance: `exclude=True,`. * for ``terse``, state.highstate expects simply ``True`` or ``False``. These can be set as such from the command line, or in the Salt config as `state_output_exclude` or `state_output_terse`, respectively. The output modes have one modifier: ``full_id``, ``terse_id``, ``mixed_id``, ``changes_id`` and ``filter_id`` If ``_id`` is used, then the corresponding form will be used, but the value for ``name`` will be drawn from the state ID. This is useful for cases where the name value might be very long and hard to read. state_tabular: If `state_output` uses the terse output, set this to `True` for an aligned output format. If you wish to use a custom format, this can be set to a string. Example usage: If ``state_output: filter`` is set in the configuration file: .. code-block:: bash salt '*' state.highstate exclude=None,True means to exclude no states from the highstate and turn on terse output. .. code-block:: bash salt twd state.highstate exclude=problemstate1,problemstate2,False means to exclude states ``problemstate1`` and ``problemstate2`` from the highstate, and use regular output. Example output for the above highstate call when ``top.sls`` defines only one other state to apply to minion ``twd``: .. code-block:: text twd: Summary for twd ------------ Succeeded: 1 (changed=1) Failed: 0 ------------ Total states run: 1 Example output with no special settings in configuration files: .. code-block:: text myminion: ---------- ID: test.ping Function: module.run Result: True Comment: Module function test.ping executed Changes: ---------- ret: True Summary for myminion ------------ Succeeded: 1 Failed: 0 ------------ Total: 0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import pprint import re import textwrap # Import salt libs import salt.utils.color import salt.utils.data import salt.utils.stringutils import salt.output # Import 3rd-party libs from salt.ext import six import logging log = logging.getLogger(__name__) def _format_host(host, data, indent_level=1): ''' Main highstate formatter. can be called recursively if a nested highstate contains other highstates (ie in an orchestration) ''' host = salt.utils.data.decode(host) colors = salt.utils.color.get_colors( __opts__.get('color'), __opts__.get('color_theme')) tabular = __opts__.get('state_tabular', False) rcounts = {} rdurations = [] hcolor = colors['GREEN'] hstrs = [] nchanges = 0 strip_colors = __opts__.get('strip_colors', True) if isinstance(data, int) or isinstance(data, six.string_types): # Data in this format is from saltmod.function, # so it is always a 'change' nchanges = 1 hstrs.append(('{0} {1}{2[ENDC]}' .format(hcolor, data, colors))) hcolor = colors['CYAN'] # Print the minion name in cyan if isinstance(data, list): # Errors have been detected, list them in RED! hcolor = colors['LIGHT_RED'] hstrs.append((' {0}Data failed to compile:{1[ENDC]}' .format(hcolor, colors))) for err in data: if strip_colors: err = salt.output.strip_esc_sequence( salt.utils.data.decode(err) ) hstrs.append(('{0}----------\n {1}{2[ENDC]}' .format(hcolor, err, colors))) if isinstance(data, dict): # Verify that the needed data is present data_tmp = {} for tname, info in six.iteritems(data): if isinstance(info, dict) and tname is not 'changes' and info and '__run_num__' not in info: err = ('The State execution failed to record the order ' 'in which all states were executed. The state ' 'return missing data is:') hstrs.insert(0, pprint.pformat(info)) hstrs.insert(0, err) if isinstance(info, dict) and 'result' in info: data_tmp[tname] = info data = data_tmp # Everything rendered as it should display the output for tname in sorted( data, key=lambda k: data[k].get('__run_num__', 0)): ret = data[tname] # Increment result counts rcounts.setdefault(ret['result'], 0) rcounts[ret['result']] += 1 rduration = ret.get('duration', 0) try: rdurations.append(float(rduration)) except ValueError: rduration, _, _ = rduration.partition(' ms') try: rdurations.append(float(rduration)) except ValueError: log.error('Cannot parse a float from duration %s', ret.get('duration', 0)) tcolor = colors['GREEN'] if ret.get('name') in ['state.orch', 'state.orchestrate', 'state.sls']: nested = output(ret['changes']['return'], indent_level=indent_level+1) ctext = re.sub('^', ' ' * 14 * indent_level, '\n'+nested, flags=re.MULTILINE) schanged = True nchanges += 1 else: schanged, ctext = _format_changes(ret['changes']) nchanges += 1 if schanged else 0 # Skip this state if it was successful & diff output was requested if __opts__.get('state_output_diff', False) and \ ret['result'] and not schanged: continue # Skip this state if state_verbose is False, the result is True and # there were no changes made if not __opts__.get('state_verbose', False) and \ ret['result'] and not schanged: continue if schanged: tcolor = colors['CYAN'] if ret['result'] is False: hcolor = colors['RED'] tcolor = colors['RED'] if ret['result'] is None: hcolor = colors['LIGHT_YELLOW'] tcolor = colors['LIGHT_YELLOW'] state_output = __opts__.get('state_output', 'full').lower() comps = tname.split('_|-') if state_output.endswith('_id'): # Swap in the ID for the name. Refs #35137 comps[2] = comps[1] if state_output.startswith('filter'): # By default, full data is shown for all types. However, return # data may be excluded by setting state_output_exclude to a # comma-separated list of True, False or None, or including the # same list with the exclude option on the command line. For # now, this option must include a comma. For example: # exclude=True, # The same functionality is also available for making return # data terse, instead of excluding it. cliargs = __opts__.get('arg', []) clikwargs = {} for item in cliargs: if isinstance(item, dict) and '__kwarg__' in item: clikwargs = item.copy() exclude = clikwargs.get( 'exclude', __opts__.get('state_output_exclude', []) ) if isinstance(exclude, six.string_types): exclude = six.text_type(exclude).split(',') terse = clikwargs.get( 'terse', __opts__.get('state_output_terse', []) ) if isinstance(terse, six.string_types): terse = six.text_type(terse).split(',') if six.text_type(ret['result']) in terse: msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue if six.text_type(ret['result']) in exclude: continue elif any(( state_output.startswith('terse'), state_output.startswith('mixed') and ret['result'] is not False, # only non-error'd state_output.startswith('changes') and ret['result'] and not schanged # non-error'd non-changed )): # Print this chunk in a terse way and continue in the loop msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue state_lines = [ '{tcolor}----------{colors[ENDC]}', ' {tcolor} ID: {comps[1]}{colors[ENDC]}', ' {tcolor}Function: {comps[0]}.{comps[3]}{colors[ENDC]}', ' {tcolor} Result: {ret[result]!s}{colors[ENDC]}', ' {tcolor} Comment: {comment}{colors[ENDC]}', ] if __opts__.get('state_output_profile', True) and 'start_time' in ret: state_lines.extend([ ' {tcolor} Started: {ret[start_time]!s}{colors[ENDC]}', ' {tcolor}Duration: {ret[duration]!s}{colors[ENDC]}', ]) # This isn't the prettiest way of doing this, but it's readable. if comps[1] != comps[2]: state_lines.insert( 3, ' {tcolor} Name: {comps[2]}{colors[ENDC]}') # be sure that ret['comment'] is utf-8 friendly try: if not isinstance(ret['comment'], six.text_type): ret['comment'] = six.text_type(ret['comment']) except UnicodeDecodeError: # If we got here, we're on Python 2 and ret['comment'] somehow # contained a str type with unicode content. ret['comment'] = salt.utils.stringutils.to_unicode(ret['comment']) try: comment = salt.utils.data.decode(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) except AttributeError: # Assume comment is a list try: comment = ret['comment'].join(' ').replace( '\n', '\n' + ' ' * 13) except AttributeError: # Comment isn't a list either, just convert to string comment = six.text_type(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) # If there is a data attribute, append it to the comment if 'data' in ret: if isinstance(ret['data'], list): for item in ret['data']: comment = '{0} {1}'.format(comment, item) elif isinstance(ret['data'], dict): for key, value in ret['data'].items(): comment = '{0}\n\t\t{1}: {2}'.format(comment, key, value) else: comment = '{0} {1}'.format(comment, ret['data']) for detail in ['start_time', 'duration']: ret.setdefault(detail, '') if ret['duration'] != '': ret['duration'] = '{0} ms'.format(ret['duration']) svars = { 'tcolor': tcolor, 'comps': comps, 'ret': ret, 'comment': salt.utils.data.decode(comment), # This nukes any trailing \n and indents the others. 'colors': colors } hstrs.extend([sline.format(**svars) for sline in state_lines]) changes = ' Changes: ' + ctext hstrs.append(('{0}{1}{2[ENDC]}' .format(tcolor, changes, colors))) if 'warnings' in ret: rcounts.setdefault('warnings', 0) rcounts['warnings'] += 1 wrapper = textwrap.TextWrapper( width=80, initial_indent=' ' * 14, subsequent_indent=' ' * 14 ) hstrs.append( ' {colors[LIGHT_RED]} Warnings: {0}{colors[ENDC]}'.format( wrapper.fill('\n'.join(ret['warnings'])).lstrip(), colors=colors ) ) # Append result counts to end of output colorfmt = '{0}{1}{2[ENDC]}' rlabel = {True: 'Succeeded', False: 'Failed', None: 'Not Run', 'warnings': 'Warnings'} count_max_len = max([len(six.text_type(x)) for x in six.itervalues(rcounts)] or [0]) label_max_len = max([len(x) for x in six.itervalues(rlabel)] or [0]) line_max_len = label_max_len + count_max_len + 2 # +2 for ': ' hstrs.append( colorfmt.format( colors['CYAN'], '\nSummary for {0}\n{1}'.format(host, '-' * line_max_len), colors ) ) def _counts(label, count): return '{0}: {1:>{2}}'.format( label, count, line_max_len - (len(label) + 2) ) # Successful states changestats = [] if None in rcounts and rcounts.get(None, 0) > 0: # test=True states changestats.append( colorfmt.format( colors['LIGHT_YELLOW'], 'unchanged={0}'.format(rcounts.get(None, 0)), colors ) ) if nchanges > 0: changestats.append( colorfmt.format( colors['GREEN'], 'changed={0}'.format(nchanges), colors ) ) if changestats: changestats = ' ({0})'.format(', '.join(changestats)) else: changestats = '' hstrs.append( colorfmt.format( colors['GREEN'], _counts( rlabel[True], rcounts.get(True, 0) + rcounts.get(None, 0) ), colors ) + changestats ) # Failed states num_failed = rcounts.get(False, 0) hstrs.append( colorfmt.format( colors['RED'] if num_failed else colors['CYAN'], _counts(rlabel[False], num_failed), colors ) ) num_warnings = rcounts.get('warnings', 0) if num_warnings: hstrs.append( colorfmt.format( colors['LIGHT_RED'], _counts(rlabel['warnings'], num_warnings), colors ) ) totals = '{0}\nTotal states run: {1:>{2}}'.format('-' * line_max_len, sum(six.itervalues(rcounts)) - rcounts.get('warnings', 0), line_max_len - 7) hstrs.append(colorfmt.format(colors['CYAN'], totals, colors)) if __opts__.get('state_output_profile', True): sum_duration = sum(rdurations) duration_unit = 'ms' # convert to seconds if duration is 1000ms or more if sum_duration > 999: sum_duration /= 1000 duration_unit = 's' total_duration = 'Total run time: {0} {1}'.format( '{0:.3f}'.format(sum_duration).rjust(line_max_len - 5), duration_unit) hstrs.append(colorfmt.format(colors['CYAN'], total_duration, colors)) if strip_colors: host = salt.output.strip_esc_sequence(host) hstrs.insert(0, ('{0}{1}:{2[ENDC]}'.format(hcolor, host, colors))) return '\n'.join(hstrs), nchanges > 0 def _nested_changes(changes): ''' Print the changes data using the nested outputter ''' ret = '\n' ret += salt.output.out_format( changes, 'nested', __opts__, nested_indent=14) return ret def _format_changes(changes, orchestration=False): ''' Format the changes dict based on what the data is ''' if not changes: return False, '' if orchestration: return True, _nested_changes(changes) if not isinstance(changes, dict): return True, 'Invalid Changes data: {0}'.format(changes) ret = changes.get('ret') if ret is not None and changes.get('out') == 'highstate': ctext = '' changed = False for host, hostdata in six.iteritems(ret): s, c = _format_host(host, hostdata) ctext += '\n' + '\n'.join((' ' * 14 + l) for l in s.splitlines()) changed = changed or c else: changed = True ctext = _nested_changes(changes) return changed, ctext def _format_terse(tcolor, comps, ret, colors, tabular): ''' Terse formatting of a message. ''' result = 'Clean' if ret['changes']: result = 'Changed' if ret['result'] is False: result = 'Failed' elif ret['result'] is None: result = 'Differs' if tabular is True: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}\n'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += '{0}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += '{6[start_time]!s} [{6[duration]!s:>7} ms] ' fmt_string += '{2:>10}.{3:<10} {4:7} Name: {1}{5}' elif isinstance(tabular, six.string_types): fmt_string = tabular else: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += ' {0} Name: {1} - Function: {2}.{3} - Result: {4}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += ' Started: - {6[start_time]!s} Duration: {6[duration]!s} ms' fmt_string += '{5}' msg = fmt_string.format(tcolor, comps[2], comps[0], comps[-1], result, colors['ENDC'], ret) return msg
saltstack/salt
salt/output/highstate.py
_format_host
python
def _format_host(host, data, indent_level=1): ''' Main highstate formatter. can be called recursively if a nested highstate contains other highstates (ie in an orchestration) ''' host = salt.utils.data.decode(host) colors = salt.utils.color.get_colors( __opts__.get('color'), __opts__.get('color_theme')) tabular = __opts__.get('state_tabular', False) rcounts = {} rdurations = [] hcolor = colors['GREEN'] hstrs = [] nchanges = 0 strip_colors = __opts__.get('strip_colors', True) if isinstance(data, int) or isinstance(data, six.string_types): # Data in this format is from saltmod.function, # so it is always a 'change' nchanges = 1 hstrs.append(('{0} {1}{2[ENDC]}' .format(hcolor, data, colors))) hcolor = colors['CYAN'] # Print the minion name in cyan if isinstance(data, list): # Errors have been detected, list them in RED! hcolor = colors['LIGHT_RED'] hstrs.append((' {0}Data failed to compile:{1[ENDC]}' .format(hcolor, colors))) for err in data: if strip_colors: err = salt.output.strip_esc_sequence( salt.utils.data.decode(err) ) hstrs.append(('{0}----------\n {1}{2[ENDC]}' .format(hcolor, err, colors))) if isinstance(data, dict): # Verify that the needed data is present data_tmp = {} for tname, info in six.iteritems(data): if isinstance(info, dict) and tname is not 'changes' and info and '__run_num__' not in info: err = ('The State execution failed to record the order ' 'in which all states were executed. The state ' 'return missing data is:') hstrs.insert(0, pprint.pformat(info)) hstrs.insert(0, err) if isinstance(info, dict) and 'result' in info: data_tmp[tname] = info data = data_tmp # Everything rendered as it should display the output for tname in sorted( data, key=lambda k: data[k].get('__run_num__', 0)): ret = data[tname] # Increment result counts rcounts.setdefault(ret['result'], 0) rcounts[ret['result']] += 1 rduration = ret.get('duration', 0) try: rdurations.append(float(rduration)) except ValueError: rduration, _, _ = rduration.partition(' ms') try: rdurations.append(float(rduration)) except ValueError: log.error('Cannot parse a float from duration %s', ret.get('duration', 0)) tcolor = colors['GREEN'] if ret.get('name') in ['state.orch', 'state.orchestrate', 'state.sls']: nested = output(ret['changes']['return'], indent_level=indent_level+1) ctext = re.sub('^', ' ' * 14 * indent_level, '\n'+nested, flags=re.MULTILINE) schanged = True nchanges += 1 else: schanged, ctext = _format_changes(ret['changes']) nchanges += 1 if schanged else 0 # Skip this state if it was successful & diff output was requested if __opts__.get('state_output_diff', False) and \ ret['result'] and not schanged: continue # Skip this state if state_verbose is False, the result is True and # there were no changes made if not __opts__.get('state_verbose', False) and \ ret['result'] and not schanged: continue if schanged: tcolor = colors['CYAN'] if ret['result'] is False: hcolor = colors['RED'] tcolor = colors['RED'] if ret['result'] is None: hcolor = colors['LIGHT_YELLOW'] tcolor = colors['LIGHT_YELLOW'] state_output = __opts__.get('state_output', 'full').lower() comps = tname.split('_|-') if state_output.endswith('_id'): # Swap in the ID for the name. Refs #35137 comps[2] = comps[1] if state_output.startswith('filter'): # By default, full data is shown for all types. However, return # data may be excluded by setting state_output_exclude to a # comma-separated list of True, False or None, or including the # same list with the exclude option on the command line. For # now, this option must include a comma. For example: # exclude=True, # The same functionality is also available for making return # data terse, instead of excluding it. cliargs = __opts__.get('arg', []) clikwargs = {} for item in cliargs: if isinstance(item, dict) and '__kwarg__' in item: clikwargs = item.copy() exclude = clikwargs.get( 'exclude', __opts__.get('state_output_exclude', []) ) if isinstance(exclude, six.string_types): exclude = six.text_type(exclude).split(',') terse = clikwargs.get( 'terse', __opts__.get('state_output_terse', []) ) if isinstance(terse, six.string_types): terse = six.text_type(terse).split(',') if six.text_type(ret['result']) in terse: msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue if six.text_type(ret['result']) in exclude: continue elif any(( state_output.startswith('terse'), state_output.startswith('mixed') and ret['result'] is not False, # only non-error'd state_output.startswith('changes') and ret['result'] and not schanged # non-error'd non-changed )): # Print this chunk in a terse way and continue in the loop msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue state_lines = [ '{tcolor}----------{colors[ENDC]}', ' {tcolor} ID: {comps[1]}{colors[ENDC]}', ' {tcolor}Function: {comps[0]}.{comps[3]}{colors[ENDC]}', ' {tcolor} Result: {ret[result]!s}{colors[ENDC]}', ' {tcolor} Comment: {comment}{colors[ENDC]}', ] if __opts__.get('state_output_profile', True) and 'start_time' in ret: state_lines.extend([ ' {tcolor} Started: {ret[start_time]!s}{colors[ENDC]}', ' {tcolor}Duration: {ret[duration]!s}{colors[ENDC]}', ]) # This isn't the prettiest way of doing this, but it's readable. if comps[1] != comps[2]: state_lines.insert( 3, ' {tcolor} Name: {comps[2]}{colors[ENDC]}') # be sure that ret['comment'] is utf-8 friendly try: if not isinstance(ret['comment'], six.text_type): ret['comment'] = six.text_type(ret['comment']) except UnicodeDecodeError: # If we got here, we're on Python 2 and ret['comment'] somehow # contained a str type with unicode content. ret['comment'] = salt.utils.stringutils.to_unicode(ret['comment']) try: comment = salt.utils.data.decode(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) except AttributeError: # Assume comment is a list try: comment = ret['comment'].join(' ').replace( '\n', '\n' + ' ' * 13) except AttributeError: # Comment isn't a list either, just convert to string comment = six.text_type(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) # If there is a data attribute, append it to the comment if 'data' in ret: if isinstance(ret['data'], list): for item in ret['data']: comment = '{0} {1}'.format(comment, item) elif isinstance(ret['data'], dict): for key, value in ret['data'].items(): comment = '{0}\n\t\t{1}: {2}'.format(comment, key, value) else: comment = '{0} {1}'.format(comment, ret['data']) for detail in ['start_time', 'duration']: ret.setdefault(detail, '') if ret['duration'] != '': ret['duration'] = '{0} ms'.format(ret['duration']) svars = { 'tcolor': tcolor, 'comps': comps, 'ret': ret, 'comment': salt.utils.data.decode(comment), # This nukes any trailing \n and indents the others. 'colors': colors } hstrs.extend([sline.format(**svars) for sline in state_lines]) changes = ' Changes: ' + ctext hstrs.append(('{0}{1}{2[ENDC]}' .format(tcolor, changes, colors))) if 'warnings' in ret: rcounts.setdefault('warnings', 0) rcounts['warnings'] += 1 wrapper = textwrap.TextWrapper( width=80, initial_indent=' ' * 14, subsequent_indent=' ' * 14 ) hstrs.append( ' {colors[LIGHT_RED]} Warnings: {0}{colors[ENDC]}'.format( wrapper.fill('\n'.join(ret['warnings'])).lstrip(), colors=colors ) ) # Append result counts to end of output colorfmt = '{0}{1}{2[ENDC]}' rlabel = {True: 'Succeeded', False: 'Failed', None: 'Not Run', 'warnings': 'Warnings'} count_max_len = max([len(six.text_type(x)) for x in six.itervalues(rcounts)] or [0]) label_max_len = max([len(x) for x in six.itervalues(rlabel)] or [0]) line_max_len = label_max_len + count_max_len + 2 # +2 for ': ' hstrs.append( colorfmt.format( colors['CYAN'], '\nSummary for {0}\n{1}'.format(host, '-' * line_max_len), colors ) ) def _counts(label, count): return '{0}: {1:>{2}}'.format( label, count, line_max_len - (len(label) + 2) ) # Successful states changestats = [] if None in rcounts and rcounts.get(None, 0) > 0: # test=True states changestats.append( colorfmt.format( colors['LIGHT_YELLOW'], 'unchanged={0}'.format(rcounts.get(None, 0)), colors ) ) if nchanges > 0: changestats.append( colorfmt.format( colors['GREEN'], 'changed={0}'.format(nchanges), colors ) ) if changestats: changestats = ' ({0})'.format(', '.join(changestats)) else: changestats = '' hstrs.append( colorfmt.format( colors['GREEN'], _counts( rlabel[True], rcounts.get(True, 0) + rcounts.get(None, 0) ), colors ) + changestats ) # Failed states num_failed = rcounts.get(False, 0) hstrs.append( colorfmt.format( colors['RED'] if num_failed else colors['CYAN'], _counts(rlabel[False], num_failed), colors ) ) num_warnings = rcounts.get('warnings', 0) if num_warnings: hstrs.append( colorfmt.format( colors['LIGHT_RED'], _counts(rlabel['warnings'], num_warnings), colors ) ) totals = '{0}\nTotal states run: {1:>{2}}'.format('-' * line_max_len, sum(six.itervalues(rcounts)) - rcounts.get('warnings', 0), line_max_len - 7) hstrs.append(colorfmt.format(colors['CYAN'], totals, colors)) if __opts__.get('state_output_profile', True): sum_duration = sum(rdurations) duration_unit = 'ms' # convert to seconds if duration is 1000ms or more if sum_duration > 999: sum_duration /= 1000 duration_unit = 's' total_duration = 'Total run time: {0} {1}'.format( '{0:.3f}'.format(sum_duration).rjust(line_max_len - 5), duration_unit) hstrs.append(colorfmt.format(colors['CYAN'], total_duration, colors)) if strip_colors: host = salt.output.strip_esc_sequence(host) hstrs.insert(0, ('{0}{1}:{2[ENDC]}'.format(hcolor, host, colors))) return '\n'.join(hstrs), nchanges > 0
Main highstate formatter. can be called recursively if a nested highstate contains other highstates (ie in an orchestration)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/highstate.py#L186-L511
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n", "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def itervalues(d, **kw):\n return d.itervalues(**kw)\n", "def output(data, **kwargs): # pylint: disable=unused-argument\n '''\n The HighState Outputter is only meant to be used with the state.highstate\n function, or a function that returns highstate return data.\n '''\n if len(data.keys()) == 1:\n # account for nested orchs via saltutil.runner\n if 'return' in data:\n data = data['return']\n\n # account for envelope data if being passed lookup_jid ret\n if isinstance(data, dict):\n _data = next(iter(data.values()))\n if 'jid' in _data and 'fun' in _data:\n data = _data['return']\n\n # output() is recursive, if we aren't passed a dict just return it\n if isinstance(data, int) or isinstance(data, six.string_types):\n return data\n\n # Discard retcode in dictionary as present in orchestrate data\n local_masters = [key for key in data.keys() if key.endswith('_master')]\n orchestrator_output = 'retcode' in data.keys() and len(local_masters) == 1\n\n if orchestrator_output:\n del data['retcode']\n\n # If additional information is passed through via the \"data\" dictionary to\n # the highstate outputter, such as \"outputter\" or \"retcode\", discard it.\n # We only want the state data that was passed through, if it is wrapped up\n # in the \"data\" key, as the orchestrate runner does. See Issue #31330,\n # pull request #27838, and pull request #27175 for more information.\n if 'data' in data:\n data = data.pop('data')\n\n indent_level = kwargs.get('indent_level', 1)\n ret = [\n _format_host(host, hostdata, indent_level=indent_level)[0]\n for host, hostdata in six.iteritems(data)\n ]\n if ret:\n return \"\\n\".join(ret)\n log.error(\n 'Data passed to highstate outputter is not a valid highstate return: %s',\n data\n )\n # We should not reach here, but if we do return empty string\n return ''\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def get_colors(use=True, theme=None):\n '''\n Return the colors as an easy to use dict. Pass `False` to deactivate all\n colors by setting them to empty strings. Pass a string containing only the\n name of a single color to be used in place of all colors. Examples:\n\n .. code-block:: python\n\n colors = get_colors() # enable all colors\n no_colors = get_colors(False) # disable all colors\n red_colors = get_colors('RED') # set all colors to red\n\n '''\n\n colors = {\n 'BLACK': TextFormat('black'),\n 'DARK_GRAY': TextFormat('bold', 'black'),\n 'RED': TextFormat('red'),\n 'LIGHT_RED': TextFormat('bold', 'red'),\n 'GREEN': TextFormat('green'),\n 'LIGHT_GREEN': TextFormat('bold', 'green'),\n 'YELLOW': TextFormat('yellow'),\n 'LIGHT_YELLOW': TextFormat('bold', 'yellow'),\n 'BLUE': TextFormat('blue'),\n 'LIGHT_BLUE': TextFormat('bold', 'blue'),\n 'MAGENTA': TextFormat('magenta'),\n 'LIGHT_MAGENTA': TextFormat('bold', 'magenta'),\n 'CYAN': TextFormat('cyan'),\n 'LIGHT_CYAN': TextFormat('bold', 'cyan'),\n 'LIGHT_GRAY': TextFormat('white'),\n 'WHITE': TextFormat('bold', 'white'),\n 'DEFAULT_COLOR': TextFormat('default'),\n 'ENDC': TextFormat('reset'),\n }\n if theme:\n colors.update(get_color_theme(theme))\n\n if not use:\n for color in colors:\n colors[color] = ''\n if isinstance(use, six.string_types):\n # Try to set all of the colors to the passed color\n if use in colors:\n for color in colors:\n # except for color reset\n if color == 'ENDC':\n continue\n colors[color] = colors[use]\n\n return colors\n", "def strip_esc_sequence(txt):\n '''\n Replace ESC (ASCII 27/Oct 33) to prevent unsafe strings\n from writing their own terminal manipulation commands\n '''\n if isinstance(txt, six.string_types):\n try:\n return txt.replace('\\033', '?')\n except UnicodeDecodeError:\n return txt.replace(str('\\033'), str('?')) # future lint: disable=blacklisted-function\n else:\n return txt\n", "def _format_changes(changes, orchestration=False):\n '''\n Format the changes dict based on what the data is\n '''\n if not changes:\n return False, ''\n\n if orchestration:\n return True, _nested_changes(changes)\n\n if not isinstance(changes, dict):\n return True, 'Invalid Changes data: {0}'.format(changes)\n\n ret = changes.get('ret')\n if ret is not None and changes.get('out') == 'highstate':\n ctext = ''\n changed = False\n for host, hostdata in six.iteritems(ret):\n s, c = _format_host(host, hostdata)\n ctext += '\\n' + '\\n'.join((' ' * 14 + l) for l in s.splitlines())\n changed = changed or c\n else:\n changed = True\n ctext = _nested_changes(changes)\n return changed, ctext\n", "def _format_terse(tcolor, comps, ret, colors, tabular):\n '''\n Terse formatting of a message.\n '''\n result = 'Clean'\n if ret['changes']:\n result = 'Changed'\n if ret['result'] is False:\n result = 'Failed'\n elif ret['result'] is None:\n result = 'Differs'\n if tabular is True:\n fmt_string = ''\n if 'warnings' in ret:\n fmt_string += '{c[LIGHT_RED]}Warnings:\\n{w}{c[ENDC]}\\n'.format(\n c=colors, w='\\n'.join(ret['warnings'])\n )\n fmt_string += '{0}'\n if __opts__.get('state_output_profile', True) and 'start_time' in ret:\n fmt_string += '{6[start_time]!s} [{6[duration]!s:>7} ms] '\n fmt_string += '{2:>10}.{3:<10} {4:7} Name: {1}{5}'\n elif isinstance(tabular, six.string_types):\n fmt_string = tabular\n else:\n fmt_string = ''\n if 'warnings' in ret:\n fmt_string += '{c[LIGHT_RED]}Warnings:\\n{w}{c[ENDC]}'.format(\n c=colors, w='\\n'.join(ret['warnings'])\n )\n fmt_string += ' {0} Name: {1} - Function: {2}.{3} - Result: {4}'\n if __opts__.get('state_output_profile', True) and 'start_time' in ret:\n fmt_string += ' Started: - {6[start_time]!s} Duration: {6[duration]!s} ms'\n fmt_string += '{5}'\n\n msg = fmt_string.format(tcolor,\n comps[2],\n comps[0],\n comps[-1],\n result,\n colors['ENDC'],\n ret)\n return msg\n", "def _counts(label, count):\n return '{0}: {1:>{2}}'.format(\n label,\n count,\n line_max_len - (len(label) + 2)\n )\n" ]
# -*- coding: utf-8 -*- ''' Outputter for displaying results of state runs ============================================== The return data from the Highstate command is a standard data structure which is parsed by the highstate outputter to deliver a clean and readable set of information about the HighState run on minions. Two configurations can be set to modify the highstate outputter. These values can be set in the master config to change the output of the ``salt`` command or set in the minion config to change the output of the ``salt-call`` command. state_verbose By default `state_verbose` is set to `True`, setting this to `False` will instruct the highstate outputter to omit displaying anything in green, this means that nothing with a result of True and no changes will not be printed state_output: The highstate outputter has six output modes, ``full``, ``terse``, ``mixed``, ``changes`` and ``filter`` * The default is set to ``full``, which will display many lines of detailed information for each executed chunk. * If ``terse`` is used, then the output is greatly simplified and shown in only one line. * If ``mixed`` is used, then terse output will be used unless a state failed, in which case full output will be used. * If ``changes`` is used, then terse output will be used if there was no error and no changes, otherwise full output will be used. * If ``filter`` is used, then either or both of two different filters can be used: ``exclude`` or ``terse``. * for ``exclude``, state.highstate expects a list of states to be excluded (or ``None``) followed by ``True`` for terse output or ``False`` for regular output. Because of parsing nuances, if only one of these is used, it must still contain a comma. For instance: `exclude=True,`. * for ``terse``, state.highstate expects simply ``True`` or ``False``. These can be set as such from the command line, or in the Salt config as `state_output_exclude` or `state_output_terse`, respectively. The output modes have one modifier: ``full_id``, ``terse_id``, ``mixed_id``, ``changes_id`` and ``filter_id`` If ``_id`` is used, then the corresponding form will be used, but the value for ``name`` will be drawn from the state ID. This is useful for cases where the name value might be very long and hard to read. state_tabular: If `state_output` uses the terse output, set this to `True` for an aligned output format. If you wish to use a custom format, this can be set to a string. Example usage: If ``state_output: filter`` is set in the configuration file: .. code-block:: bash salt '*' state.highstate exclude=None,True means to exclude no states from the highstate and turn on terse output. .. code-block:: bash salt twd state.highstate exclude=problemstate1,problemstate2,False means to exclude states ``problemstate1`` and ``problemstate2`` from the highstate, and use regular output. Example output for the above highstate call when ``top.sls`` defines only one other state to apply to minion ``twd``: .. code-block:: text twd: Summary for twd ------------ Succeeded: 1 (changed=1) Failed: 0 ------------ Total states run: 1 Example output with no special settings in configuration files: .. code-block:: text myminion: ---------- ID: test.ping Function: module.run Result: True Comment: Module function test.ping executed Changes: ---------- ret: True Summary for myminion ------------ Succeeded: 1 Failed: 0 ------------ Total: 0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import pprint import re import textwrap # Import salt libs import salt.utils.color import salt.utils.data import salt.utils.stringutils import salt.output # Import 3rd-party libs from salt.ext import six import logging log = logging.getLogger(__name__) def output(data, **kwargs): # pylint: disable=unused-argument ''' The HighState Outputter is only meant to be used with the state.highstate function, or a function that returns highstate return data. ''' if len(data.keys()) == 1: # account for nested orchs via saltutil.runner if 'return' in data: data = data['return'] # account for envelope data if being passed lookup_jid ret if isinstance(data, dict): _data = next(iter(data.values())) if 'jid' in _data and 'fun' in _data: data = _data['return'] # output() is recursive, if we aren't passed a dict just return it if isinstance(data, int) or isinstance(data, six.string_types): return data # Discard retcode in dictionary as present in orchestrate data local_masters = [key for key in data.keys() if key.endswith('_master')] orchestrator_output = 'retcode' in data.keys() and len(local_masters) == 1 if orchestrator_output: del data['retcode'] # If additional information is passed through via the "data" dictionary to # the highstate outputter, such as "outputter" or "retcode", discard it. # We only want the state data that was passed through, if it is wrapped up # in the "data" key, as the orchestrate runner does. See Issue #31330, # pull request #27838, and pull request #27175 for more information. if 'data' in data: data = data.pop('data') indent_level = kwargs.get('indent_level', 1) ret = [ _format_host(host, hostdata, indent_level=indent_level)[0] for host, hostdata in six.iteritems(data) ] if ret: return "\n".join(ret) log.error( 'Data passed to highstate outputter is not a valid highstate return: %s', data ) # We should not reach here, but if we do return empty string return '' def _nested_changes(changes): ''' Print the changes data using the nested outputter ''' ret = '\n' ret += salt.output.out_format( changes, 'nested', __opts__, nested_indent=14) return ret def _format_changes(changes, orchestration=False): ''' Format the changes dict based on what the data is ''' if not changes: return False, '' if orchestration: return True, _nested_changes(changes) if not isinstance(changes, dict): return True, 'Invalid Changes data: {0}'.format(changes) ret = changes.get('ret') if ret is not None and changes.get('out') == 'highstate': ctext = '' changed = False for host, hostdata in six.iteritems(ret): s, c = _format_host(host, hostdata) ctext += '\n' + '\n'.join((' ' * 14 + l) for l in s.splitlines()) changed = changed or c else: changed = True ctext = _nested_changes(changes) return changed, ctext def _format_terse(tcolor, comps, ret, colors, tabular): ''' Terse formatting of a message. ''' result = 'Clean' if ret['changes']: result = 'Changed' if ret['result'] is False: result = 'Failed' elif ret['result'] is None: result = 'Differs' if tabular is True: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}\n'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += '{0}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += '{6[start_time]!s} [{6[duration]!s:>7} ms] ' fmt_string += '{2:>10}.{3:<10} {4:7} Name: {1}{5}' elif isinstance(tabular, six.string_types): fmt_string = tabular else: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += ' {0} Name: {1} - Function: {2}.{3} - Result: {4}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += ' Started: - {6[start_time]!s} Duration: {6[duration]!s} ms' fmt_string += '{5}' msg = fmt_string.format(tcolor, comps[2], comps[0], comps[-1], result, colors['ENDC'], ret) return msg
saltstack/salt
salt/output/highstate.py
_nested_changes
python
def _nested_changes(changes): ''' Print the changes data using the nested outputter ''' ret = '\n' ret += salt.output.out_format( changes, 'nested', __opts__, nested_indent=14) return ret
Print the changes data using the nested outputter
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/highstate.py#L514-L524
null
# -*- coding: utf-8 -*- ''' Outputter for displaying results of state runs ============================================== The return data from the Highstate command is a standard data structure which is parsed by the highstate outputter to deliver a clean and readable set of information about the HighState run on minions. Two configurations can be set to modify the highstate outputter. These values can be set in the master config to change the output of the ``salt`` command or set in the minion config to change the output of the ``salt-call`` command. state_verbose By default `state_verbose` is set to `True`, setting this to `False` will instruct the highstate outputter to omit displaying anything in green, this means that nothing with a result of True and no changes will not be printed state_output: The highstate outputter has six output modes, ``full``, ``terse``, ``mixed``, ``changes`` and ``filter`` * The default is set to ``full``, which will display many lines of detailed information for each executed chunk. * If ``terse`` is used, then the output is greatly simplified and shown in only one line. * If ``mixed`` is used, then terse output will be used unless a state failed, in which case full output will be used. * If ``changes`` is used, then terse output will be used if there was no error and no changes, otherwise full output will be used. * If ``filter`` is used, then either or both of two different filters can be used: ``exclude`` or ``terse``. * for ``exclude``, state.highstate expects a list of states to be excluded (or ``None``) followed by ``True`` for terse output or ``False`` for regular output. Because of parsing nuances, if only one of these is used, it must still contain a comma. For instance: `exclude=True,`. * for ``terse``, state.highstate expects simply ``True`` or ``False``. These can be set as such from the command line, or in the Salt config as `state_output_exclude` or `state_output_terse`, respectively. The output modes have one modifier: ``full_id``, ``terse_id``, ``mixed_id``, ``changes_id`` and ``filter_id`` If ``_id`` is used, then the corresponding form will be used, but the value for ``name`` will be drawn from the state ID. This is useful for cases where the name value might be very long and hard to read. state_tabular: If `state_output` uses the terse output, set this to `True` for an aligned output format. If you wish to use a custom format, this can be set to a string. Example usage: If ``state_output: filter`` is set in the configuration file: .. code-block:: bash salt '*' state.highstate exclude=None,True means to exclude no states from the highstate and turn on terse output. .. code-block:: bash salt twd state.highstate exclude=problemstate1,problemstate2,False means to exclude states ``problemstate1`` and ``problemstate2`` from the highstate, and use regular output. Example output for the above highstate call when ``top.sls`` defines only one other state to apply to minion ``twd``: .. code-block:: text twd: Summary for twd ------------ Succeeded: 1 (changed=1) Failed: 0 ------------ Total states run: 1 Example output with no special settings in configuration files: .. code-block:: text myminion: ---------- ID: test.ping Function: module.run Result: True Comment: Module function test.ping executed Changes: ---------- ret: True Summary for myminion ------------ Succeeded: 1 Failed: 0 ------------ Total: 0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import pprint import re import textwrap # Import salt libs import salt.utils.color import salt.utils.data import salt.utils.stringutils import salt.output # Import 3rd-party libs from salt.ext import six import logging log = logging.getLogger(__name__) def output(data, **kwargs): # pylint: disable=unused-argument ''' The HighState Outputter is only meant to be used with the state.highstate function, or a function that returns highstate return data. ''' if len(data.keys()) == 1: # account for nested orchs via saltutil.runner if 'return' in data: data = data['return'] # account for envelope data if being passed lookup_jid ret if isinstance(data, dict): _data = next(iter(data.values())) if 'jid' in _data and 'fun' in _data: data = _data['return'] # output() is recursive, if we aren't passed a dict just return it if isinstance(data, int) or isinstance(data, six.string_types): return data # Discard retcode in dictionary as present in orchestrate data local_masters = [key for key in data.keys() if key.endswith('_master')] orchestrator_output = 'retcode' in data.keys() and len(local_masters) == 1 if orchestrator_output: del data['retcode'] # If additional information is passed through via the "data" dictionary to # the highstate outputter, such as "outputter" or "retcode", discard it. # We only want the state data that was passed through, if it is wrapped up # in the "data" key, as the orchestrate runner does. See Issue #31330, # pull request #27838, and pull request #27175 for more information. if 'data' in data: data = data.pop('data') indent_level = kwargs.get('indent_level', 1) ret = [ _format_host(host, hostdata, indent_level=indent_level)[0] for host, hostdata in six.iteritems(data) ] if ret: return "\n".join(ret) log.error( 'Data passed to highstate outputter is not a valid highstate return: %s', data ) # We should not reach here, but if we do return empty string return '' def _format_host(host, data, indent_level=1): ''' Main highstate formatter. can be called recursively if a nested highstate contains other highstates (ie in an orchestration) ''' host = salt.utils.data.decode(host) colors = salt.utils.color.get_colors( __opts__.get('color'), __opts__.get('color_theme')) tabular = __opts__.get('state_tabular', False) rcounts = {} rdurations = [] hcolor = colors['GREEN'] hstrs = [] nchanges = 0 strip_colors = __opts__.get('strip_colors', True) if isinstance(data, int) or isinstance(data, six.string_types): # Data in this format is from saltmod.function, # so it is always a 'change' nchanges = 1 hstrs.append(('{0} {1}{2[ENDC]}' .format(hcolor, data, colors))) hcolor = colors['CYAN'] # Print the minion name in cyan if isinstance(data, list): # Errors have been detected, list them in RED! hcolor = colors['LIGHT_RED'] hstrs.append((' {0}Data failed to compile:{1[ENDC]}' .format(hcolor, colors))) for err in data: if strip_colors: err = salt.output.strip_esc_sequence( salt.utils.data.decode(err) ) hstrs.append(('{0}----------\n {1}{2[ENDC]}' .format(hcolor, err, colors))) if isinstance(data, dict): # Verify that the needed data is present data_tmp = {} for tname, info in six.iteritems(data): if isinstance(info, dict) and tname is not 'changes' and info and '__run_num__' not in info: err = ('The State execution failed to record the order ' 'in which all states were executed. The state ' 'return missing data is:') hstrs.insert(0, pprint.pformat(info)) hstrs.insert(0, err) if isinstance(info, dict) and 'result' in info: data_tmp[tname] = info data = data_tmp # Everything rendered as it should display the output for tname in sorted( data, key=lambda k: data[k].get('__run_num__', 0)): ret = data[tname] # Increment result counts rcounts.setdefault(ret['result'], 0) rcounts[ret['result']] += 1 rduration = ret.get('duration', 0) try: rdurations.append(float(rduration)) except ValueError: rduration, _, _ = rduration.partition(' ms') try: rdurations.append(float(rduration)) except ValueError: log.error('Cannot parse a float from duration %s', ret.get('duration', 0)) tcolor = colors['GREEN'] if ret.get('name') in ['state.orch', 'state.orchestrate', 'state.sls']: nested = output(ret['changes']['return'], indent_level=indent_level+1) ctext = re.sub('^', ' ' * 14 * indent_level, '\n'+nested, flags=re.MULTILINE) schanged = True nchanges += 1 else: schanged, ctext = _format_changes(ret['changes']) nchanges += 1 if schanged else 0 # Skip this state if it was successful & diff output was requested if __opts__.get('state_output_diff', False) and \ ret['result'] and not schanged: continue # Skip this state if state_verbose is False, the result is True and # there were no changes made if not __opts__.get('state_verbose', False) and \ ret['result'] and not schanged: continue if schanged: tcolor = colors['CYAN'] if ret['result'] is False: hcolor = colors['RED'] tcolor = colors['RED'] if ret['result'] is None: hcolor = colors['LIGHT_YELLOW'] tcolor = colors['LIGHT_YELLOW'] state_output = __opts__.get('state_output', 'full').lower() comps = tname.split('_|-') if state_output.endswith('_id'): # Swap in the ID for the name. Refs #35137 comps[2] = comps[1] if state_output.startswith('filter'): # By default, full data is shown for all types. However, return # data may be excluded by setting state_output_exclude to a # comma-separated list of True, False or None, or including the # same list with the exclude option on the command line. For # now, this option must include a comma. For example: # exclude=True, # The same functionality is also available for making return # data terse, instead of excluding it. cliargs = __opts__.get('arg', []) clikwargs = {} for item in cliargs: if isinstance(item, dict) and '__kwarg__' in item: clikwargs = item.copy() exclude = clikwargs.get( 'exclude', __opts__.get('state_output_exclude', []) ) if isinstance(exclude, six.string_types): exclude = six.text_type(exclude).split(',') terse = clikwargs.get( 'terse', __opts__.get('state_output_terse', []) ) if isinstance(terse, six.string_types): terse = six.text_type(terse).split(',') if six.text_type(ret['result']) in terse: msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue if six.text_type(ret['result']) in exclude: continue elif any(( state_output.startswith('terse'), state_output.startswith('mixed') and ret['result'] is not False, # only non-error'd state_output.startswith('changes') and ret['result'] and not schanged # non-error'd non-changed )): # Print this chunk in a terse way and continue in the loop msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue state_lines = [ '{tcolor}----------{colors[ENDC]}', ' {tcolor} ID: {comps[1]}{colors[ENDC]}', ' {tcolor}Function: {comps[0]}.{comps[3]}{colors[ENDC]}', ' {tcolor} Result: {ret[result]!s}{colors[ENDC]}', ' {tcolor} Comment: {comment}{colors[ENDC]}', ] if __opts__.get('state_output_profile', True) and 'start_time' in ret: state_lines.extend([ ' {tcolor} Started: {ret[start_time]!s}{colors[ENDC]}', ' {tcolor}Duration: {ret[duration]!s}{colors[ENDC]}', ]) # This isn't the prettiest way of doing this, but it's readable. if comps[1] != comps[2]: state_lines.insert( 3, ' {tcolor} Name: {comps[2]}{colors[ENDC]}') # be sure that ret['comment'] is utf-8 friendly try: if not isinstance(ret['comment'], six.text_type): ret['comment'] = six.text_type(ret['comment']) except UnicodeDecodeError: # If we got here, we're on Python 2 and ret['comment'] somehow # contained a str type with unicode content. ret['comment'] = salt.utils.stringutils.to_unicode(ret['comment']) try: comment = salt.utils.data.decode(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) except AttributeError: # Assume comment is a list try: comment = ret['comment'].join(' ').replace( '\n', '\n' + ' ' * 13) except AttributeError: # Comment isn't a list either, just convert to string comment = six.text_type(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) # If there is a data attribute, append it to the comment if 'data' in ret: if isinstance(ret['data'], list): for item in ret['data']: comment = '{0} {1}'.format(comment, item) elif isinstance(ret['data'], dict): for key, value in ret['data'].items(): comment = '{0}\n\t\t{1}: {2}'.format(comment, key, value) else: comment = '{0} {1}'.format(comment, ret['data']) for detail in ['start_time', 'duration']: ret.setdefault(detail, '') if ret['duration'] != '': ret['duration'] = '{0} ms'.format(ret['duration']) svars = { 'tcolor': tcolor, 'comps': comps, 'ret': ret, 'comment': salt.utils.data.decode(comment), # This nukes any trailing \n and indents the others. 'colors': colors } hstrs.extend([sline.format(**svars) for sline in state_lines]) changes = ' Changes: ' + ctext hstrs.append(('{0}{1}{2[ENDC]}' .format(tcolor, changes, colors))) if 'warnings' in ret: rcounts.setdefault('warnings', 0) rcounts['warnings'] += 1 wrapper = textwrap.TextWrapper( width=80, initial_indent=' ' * 14, subsequent_indent=' ' * 14 ) hstrs.append( ' {colors[LIGHT_RED]} Warnings: {0}{colors[ENDC]}'.format( wrapper.fill('\n'.join(ret['warnings'])).lstrip(), colors=colors ) ) # Append result counts to end of output colorfmt = '{0}{1}{2[ENDC]}' rlabel = {True: 'Succeeded', False: 'Failed', None: 'Not Run', 'warnings': 'Warnings'} count_max_len = max([len(six.text_type(x)) for x in six.itervalues(rcounts)] or [0]) label_max_len = max([len(x) for x in six.itervalues(rlabel)] or [0]) line_max_len = label_max_len + count_max_len + 2 # +2 for ': ' hstrs.append( colorfmt.format( colors['CYAN'], '\nSummary for {0}\n{1}'.format(host, '-' * line_max_len), colors ) ) def _counts(label, count): return '{0}: {1:>{2}}'.format( label, count, line_max_len - (len(label) + 2) ) # Successful states changestats = [] if None in rcounts and rcounts.get(None, 0) > 0: # test=True states changestats.append( colorfmt.format( colors['LIGHT_YELLOW'], 'unchanged={0}'.format(rcounts.get(None, 0)), colors ) ) if nchanges > 0: changestats.append( colorfmt.format( colors['GREEN'], 'changed={0}'.format(nchanges), colors ) ) if changestats: changestats = ' ({0})'.format(', '.join(changestats)) else: changestats = '' hstrs.append( colorfmt.format( colors['GREEN'], _counts( rlabel[True], rcounts.get(True, 0) + rcounts.get(None, 0) ), colors ) + changestats ) # Failed states num_failed = rcounts.get(False, 0) hstrs.append( colorfmt.format( colors['RED'] if num_failed else colors['CYAN'], _counts(rlabel[False], num_failed), colors ) ) num_warnings = rcounts.get('warnings', 0) if num_warnings: hstrs.append( colorfmt.format( colors['LIGHT_RED'], _counts(rlabel['warnings'], num_warnings), colors ) ) totals = '{0}\nTotal states run: {1:>{2}}'.format('-' * line_max_len, sum(six.itervalues(rcounts)) - rcounts.get('warnings', 0), line_max_len - 7) hstrs.append(colorfmt.format(colors['CYAN'], totals, colors)) if __opts__.get('state_output_profile', True): sum_duration = sum(rdurations) duration_unit = 'ms' # convert to seconds if duration is 1000ms or more if sum_duration > 999: sum_duration /= 1000 duration_unit = 's' total_duration = 'Total run time: {0} {1}'.format( '{0:.3f}'.format(sum_duration).rjust(line_max_len - 5), duration_unit) hstrs.append(colorfmt.format(colors['CYAN'], total_duration, colors)) if strip_colors: host = salt.output.strip_esc_sequence(host) hstrs.insert(0, ('{0}{1}:{2[ENDC]}'.format(hcolor, host, colors))) return '\n'.join(hstrs), nchanges > 0 def _format_changes(changes, orchestration=False): ''' Format the changes dict based on what the data is ''' if not changes: return False, '' if orchestration: return True, _nested_changes(changes) if not isinstance(changes, dict): return True, 'Invalid Changes data: {0}'.format(changes) ret = changes.get('ret') if ret is not None and changes.get('out') == 'highstate': ctext = '' changed = False for host, hostdata in six.iteritems(ret): s, c = _format_host(host, hostdata) ctext += '\n' + '\n'.join((' ' * 14 + l) for l in s.splitlines()) changed = changed or c else: changed = True ctext = _nested_changes(changes) return changed, ctext def _format_terse(tcolor, comps, ret, colors, tabular): ''' Terse formatting of a message. ''' result = 'Clean' if ret['changes']: result = 'Changed' if ret['result'] is False: result = 'Failed' elif ret['result'] is None: result = 'Differs' if tabular is True: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}\n'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += '{0}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += '{6[start_time]!s} [{6[duration]!s:>7} ms] ' fmt_string += '{2:>10}.{3:<10} {4:7} Name: {1}{5}' elif isinstance(tabular, six.string_types): fmt_string = tabular else: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += ' {0} Name: {1} - Function: {2}.{3} - Result: {4}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += ' Started: - {6[start_time]!s} Duration: {6[duration]!s} ms' fmt_string += '{5}' msg = fmt_string.format(tcolor, comps[2], comps[0], comps[-1], result, colors['ENDC'], ret) return msg
saltstack/salt
salt/output/highstate.py
_format_changes
python
def _format_changes(changes, orchestration=False): ''' Format the changes dict based on what the data is ''' if not changes: return False, '' if orchestration: return True, _nested_changes(changes) if not isinstance(changes, dict): return True, 'Invalid Changes data: {0}'.format(changes) ret = changes.get('ret') if ret is not None and changes.get('out') == 'highstate': ctext = '' changed = False for host, hostdata in six.iteritems(ret): s, c = _format_host(host, hostdata) ctext += '\n' + '\n'.join((' ' * 14 + l) for l in s.splitlines()) changed = changed or c else: changed = True ctext = _nested_changes(changes) return changed, ctext
Format the changes dict based on what the data is
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/highstate.py#L527-L551
null
# -*- coding: utf-8 -*- ''' Outputter for displaying results of state runs ============================================== The return data from the Highstate command is a standard data structure which is parsed by the highstate outputter to deliver a clean and readable set of information about the HighState run on minions. Two configurations can be set to modify the highstate outputter. These values can be set in the master config to change the output of the ``salt`` command or set in the minion config to change the output of the ``salt-call`` command. state_verbose By default `state_verbose` is set to `True`, setting this to `False` will instruct the highstate outputter to omit displaying anything in green, this means that nothing with a result of True and no changes will not be printed state_output: The highstate outputter has six output modes, ``full``, ``terse``, ``mixed``, ``changes`` and ``filter`` * The default is set to ``full``, which will display many lines of detailed information for each executed chunk. * If ``terse`` is used, then the output is greatly simplified and shown in only one line. * If ``mixed`` is used, then terse output will be used unless a state failed, in which case full output will be used. * If ``changes`` is used, then terse output will be used if there was no error and no changes, otherwise full output will be used. * If ``filter`` is used, then either or both of two different filters can be used: ``exclude`` or ``terse``. * for ``exclude``, state.highstate expects a list of states to be excluded (or ``None``) followed by ``True`` for terse output or ``False`` for regular output. Because of parsing nuances, if only one of these is used, it must still contain a comma. For instance: `exclude=True,`. * for ``terse``, state.highstate expects simply ``True`` or ``False``. These can be set as such from the command line, or in the Salt config as `state_output_exclude` or `state_output_terse`, respectively. The output modes have one modifier: ``full_id``, ``terse_id``, ``mixed_id``, ``changes_id`` and ``filter_id`` If ``_id`` is used, then the corresponding form will be used, but the value for ``name`` will be drawn from the state ID. This is useful for cases where the name value might be very long and hard to read. state_tabular: If `state_output` uses the terse output, set this to `True` for an aligned output format. If you wish to use a custom format, this can be set to a string. Example usage: If ``state_output: filter`` is set in the configuration file: .. code-block:: bash salt '*' state.highstate exclude=None,True means to exclude no states from the highstate and turn on terse output. .. code-block:: bash salt twd state.highstate exclude=problemstate1,problemstate2,False means to exclude states ``problemstate1`` and ``problemstate2`` from the highstate, and use regular output. Example output for the above highstate call when ``top.sls`` defines only one other state to apply to minion ``twd``: .. code-block:: text twd: Summary for twd ------------ Succeeded: 1 (changed=1) Failed: 0 ------------ Total states run: 1 Example output with no special settings in configuration files: .. code-block:: text myminion: ---------- ID: test.ping Function: module.run Result: True Comment: Module function test.ping executed Changes: ---------- ret: True Summary for myminion ------------ Succeeded: 1 Failed: 0 ------------ Total: 0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import pprint import re import textwrap # Import salt libs import salt.utils.color import salt.utils.data import salt.utils.stringutils import salt.output # Import 3rd-party libs from salt.ext import six import logging log = logging.getLogger(__name__) def output(data, **kwargs): # pylint: disable=unused-argument ''' The HighState Outputter is only meant to be used with the state.highstate function, or a function that returns highstate return data. ''' if len(data.keys()) == 1: # account for nested orchs via saltutil.runner if 'return' in data: data = data['return'] # account for envelope data if being passed lookup_jid ret if isinstance(data, dict): _data = next(iter(data.values())) if 'jid' in _data and 'fun' in _data: data = _data['return'] # output() is recursive, if we aren't passed a dict just return it if isinstance(data, int) or isinstance(data, six.string_types): return data # Discard retcode in dictionary as present in orchestrate data local_masters = [key for key in data.keys() if key.endswith('_master')] orchestrator_output = 'retcode' in data.keys() and len(local_masters) == 1 if orchestrator_output: del data['retcode'] # If additional information is passed through via the "data" dictionary to # the highstate outputter, such as "outputter" or "retcode", discard it. # We only want the state data that was passed through, if it is wrapped up # in the "data" key, as the orchestrate runner does. See Issue #31330, # pull request #27838, and pull request #27175 for more information. if 'data' in data: data = data.pop('data') indent_level = kwargs.get('indent_level', 1) ret = [ _format_host(host, hostdata, indent_level=indent_level)[0] for host, hostdata in six.iteritems(data) ] if ret: return "\n".join(ret) log.error( 'Data passed to highstate outputter is not a valid highstate return: %s', data ) # We should not reach here, but if we do return empty string return '' def _format_host(host, data, indent_level=1): ''' Main highstate formatter. can be called recursively if a nested highstate contains other highstates (ie in an orchestration) ''' host = salt.utils.data.decode(host) colors = salt.utils.color.get_colors( __opts__.get('color'), __opts__.get('color_theme')) tabular = __opts__.get('state_tabular', False) rcounts = {} rdurations = [] hcolor = colors['GREEN'] hstrs = [] nchanges = 0 strip_colors = __opts__.get('strip_colors', True) if isinstance(data, int) or isinstance(data, six.string_types): # Data in this format is from saltmod.function, # so it is always a 'change' nchanges = 1 hstrs.append(('{0} {1}{2[ENDC]}' .format(hcolor, data, colors))) hcolor = colors['CYAN'] # Print the minion name in cyan if isinstance(data, list): # Errors have been detected, list them in RED! hcolor = colors['LIGHT_RED'] hstrs.append((' {0}Data failed to compile:{1[ENDC]}' .format(hcolor, colors))) for err in data: if strip_colors: err = salt.output.strip_esc_sequence( salt.utils.data.decode(err) ) hstrs.append(('{0}----------\n {1}{2[ENDC]}' .format(hcolor, err, colors))) if isinstance(data, dict): # Verify that the needed data is present data_tmp = {} for tname, info in six.iteritems(data): if isinstance(info, dict) and tname is not 'changes' and info and '__run_num__' not in info: err = ('The State execution failed to record the order ' 'in which all states were executed. The state ' 'return missing data is:') hstrs.insert(0, pprint.pformat(info)) hstrs.insert(0, err) if isinstance(info, dict) and 'result' in info: data_tmp[tname] = info data = data_tmp # Everything rendered as it should display the output for tname in sorted( data, key=lambda k: data[k].get('__run_num__', 0)): ret = data[tname] # Increment result counts rcounts.setdefault(ret['result'], 0) rcounts[ret['result']] += 1 rduration = ret.get('duration', 0) try: rdurations.append(float(rduration)) except ValueError: rduration, _, _ = rduration.partition(' ms') try: rdurations.append(float(rduration)) except ValueError: log.error('Cannot parse a float from duration %s', ret.get('duration', 0)) tcolor = colors['GREEN'] if ret.get('name') in ['state.orch', 'state.orchestrate', 'state.sls']: nested = output(ret['changes']['return'], indent_level=indent_level+1) ctext = re.sub('^', ' ' * 14 * indent_level, '\n'+nested, flags=re.MULTILINE) schanged = True nchanges += 1 else: schanged, ctext = _format_changes(ret['changes']) nchanges += 1 if schanged else 0 # Skip this state if it was successful & diff output was requested if __opts__.get('state_output_diff', False) and \ ret['result'] and not schanged: continue # Skip this state if state_verbose is False, the result is True and # there were no changes made if not __opts__.get('state_verbose', False) and \ ret['result'] and not schanged: continue if schanged: tcolor = colors['CYAN'] if ret['result'] is False: hcolor = colors['RED'] tcolor = colors['RED'] if ret['result'] is None: hcolor = colors['LIGHT_YELLOW'] tcolor = colors['LIGHT_YELLOW'] state_output = __opts__.get('state_output', 'full').lower() comps = tname.split('_|-') if state_output.endswith('_id'): # Swap in the ID for the name. Refs #35137 comps[2] = comps[1] if state_output.startswith('filter'): # By default, full data is shown for all types. However, return # data may be excluded by setting state_output_exclude to a # comma-separated list of True, False or None, or including the # same list with the exclude option on the command line. For # now, this option must include a comma. For example: # exclude=True, # The same functionality is also available for making return # data terse, instead of excluding it. cliargs = __opts__.get('arg', []) clikwargs = {} for item in cliargs: if isinstance(item, dict) and '__kwarg__' in item: clikwargs = item.copy() exclude = clikwargs.get( 'exclude', __opts__.get('state_output_exclude', []) ) if isinstance(exclude, six.string_types): exclude = six.text_type(exclude).split(',') terse = clikwargs.get( 'terse', __opts__.get('state_output_terse', []) ) if isinstance(terse, six.string_types): terse = six.text_type(terse).split(',') if six.text_type(ret['result']) in terse: msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue if six.text_type(ret['result']) in exclude: continue elif any(( state_output.startswith('terse'), state_output.startswith('mixed') and ret['result'] is not False, # only non-error'd state_output.startswith('changes') and ret['result'] and not schanged # non-error'd non-changed )): # Print this chunk in a terse way and continue in the loop msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue state_lines = [ '{tcolor}----------{colors[ENDC]}', ' {tcolor} ID: {comps[1]}{colors[ENDC]}', ' {tcolor}Function: {comps[0]}.{comps[3]}{colors[ENDC]}', ' {tcolor} Result: {ret[result]!s}{colors[ENDC]}', ' {tcolor} Comment: {comment}{colors[ENDC]}', ] if __opts__.get('state_output_profile', True) and 'start_time' in ret: state_lines.extend([ ' {tcolor} Started: {ret[start_time]!s}{colors[ENDC]}', ' {tcolor}Duration: {ret[duration]!s}{colors[ENDC]}', ]) # This isn't the prettiest way of doing this, but it's readable. if comps[1] != comps[2]: state_lines.insert( 3, ' {tcolor} Name: {comps[2]}{colors[ENDC]}') # be sure that ret['comment'] is utf-8 friendly try: if not isinstance(ret['comment'], six.text_type): ret['comment'] = six.text_type(ret['comment']) except UnicodeDecodeError: # If we got here, we're on Python 2 and ret['comment'] somehow # contained a str type with unicode content. ret['comment'] = salt.utils.stringutils.to_unicode(ret['comment']) try: comment = salt.utils.data.decode(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) except AttributeError: # Assume comment is a list try: comment = ret['comment'].join(' ').replace( '\n', '\n' + ' ' * 13) except AttributeError: # Comment isn't a list either, just convert to string comment = six.text_type(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) # If there is a data attribute, append it to the comment if 'data' in ret: if isinstance(ret['data'], list): for item in ret['data']: comment = '{0} {1}'.format(comment, item) elif isinstance(ret['data'], dict): for key, value in ret['data'].items(): comment = '{0}\n\t\t{1}: {2}'.format(comment, key, value) else: comment = '{0} {1}'.format(comment, ret['data']) for detail in ['start_time', 'duration']: ret.setdefault(detail, '') if ret['duration'] != '': ret['duration'] = '{0} ms'.format(ret['duration']) svars = { 'tcolor': tcolor, 'comps': comps, 'ret': ret, 'comment': salt.utils.data.decode(comment), # This nukes any trailing \n and indents the others. 'colors': colors } hstrs.extend([sline.format(**svars) for sline in state_lines]) changes = ' Changes: ' + ctext hstrs.append(('{0}{1}{2[ENDC]}' .format(tcolor, changes, colors))) if 'warnings' in ret: rcounts.setdefault('warnings', 0) rcounts['warnings'] += 1 wrapper = textwrap.TextWrapper( width=80, initial_indent=' ' * 14, subsequent_indent=' ' * 14 ) hstrs.append( ' {colors[LIGHT_RED]} Warnings: {0}{colors[ENDC]}'.format( wrapper.fill('\n'.join(ret['warnings'])).lstrip(), colors=colors ) ) # Append result counts to end of output colorfmt = '{0}{1}{2[ENDC]}' rlabel = {True: 'Succeeded', False: 'Failed', None: 'Not Run', 'warnings': 'Warnings'} count_max_len = max([len(six.text_type(x)) for x in six.itervalues(rcounts)] or [0]) label_max_len = max([len(x) for x in six.itervalues(rlabel)] or [0]) line_max_len = label_max_len + count_max_len + 2 # +2 for ': ' hstrs.append( colorfmt.format( colors['CYAN'], '\nSummary for {0}\n{1}'.format(host, '-' * line_max_len), colors ) ) def _counts(label, count): return '{0}: {1:>{2}}'.format( label, count, line_max_len - (len(label) + 2) ) # Successful states changestats = [] if None in rcounts and rcounts.get(None, 0) > 0: # test=True states changestats.append( colorfmt.format( colors['LIGHT_YELLOW'], 'unchanged={0}'.format(rcounts.get(None, 0)), colors ) ) if nchanges > 0: changestats.append( colorfmt.format( colors['GREEN'], 'changed={0}'.format(nchanges), colors ) ) if changestats: changestats = ' ({0})'.format(', '.join(changestats)) else: changestats = '' hstrs.append( colorfmt.format( colors['GREEN'], _counts( rlabel[True], rcounts.get(True, 0) + rcounts.get(None, 0) ), colors ) + changestats ) # Failed states num_failed = rcounts.get(False, 0) hstrs.append( colorfmt.format( colors['RED'] if num_failed else colors['CYAN'], _counts(rlabel[False], num_failed), colors ) ) num_warnings = rcounts.get('warnings', 0) if num_warnings: hstrs.append( colorfmt.format( colors['LIGHT_RED'], _counts(rlabel['warnings'], num_warnings), colors ) ) totals = '{0}\nTotal states run: {1:>{2}}'.format('-' * line_max_len, sum(six.itervalues(rcounts)) - rcounts.get('warnings', 0), line_max_len - 7) hstrs.append(colorfmt.format(colors['CYAN'], totals, colors)) if __opts__.get('state_output_profile', True): sum_duration = sum(rdurations) duration_unit = 'ms' # convert to seconds if duration is 1000ms or more if sum_duration > 999: sum_duration /= 1000 duration_unit = 's' total_duration = 'Total run time: {0} {1}'.format( '{0:.3f}'.format(sum_duration).rjust(line_max_len - 5), duration_unit) hstrs.append(colorfmt.format(colors['CYAN'], total_duration, colors)) if strip_colors: host = salt.output.strip_esc_sequence(host) hstrs.insert(0, ('{0}{1}:{2[ENDC]}'.format(hcolor, host, colors))) return '\n'.join(hstrs), nchanges > 0 def _nested_changes(changes): ''' Print the changes data using the nested outputter ''' ret = '\n' ret += salt.output.out_format( changes, 'nested', __opts__, nested_indent=14) return ret def _format_terse(tcolor, comps, ret, colors, tabular): ''' Terse formatting of a message. ''' result = 'Clean' if ret['changes']: result = 'Changed' if ret['result'] is False: result = 'Failed' elif ret['result'] is None: result = 'Differs' if tabular is True: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}\n'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += '{0}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += '{6[start_time]!s} [{6[duration]!s:>7} ms] ' fmt_string += '{2:>10}.{3:<10} {4:7} Name: {1}{5}' elif isinstance(tabular, six.string_types): fmt_string = tabular else: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += ' {0} Name: {1} - Function: {2}.{3} - Result: {4}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += ' Started: - {6[start_time]!s} Duration: {6[duration]!s} ms' fmt_string += '{5}' msg = fmt_string.format(tcolor, comps[2], comps[0], comps[-1], result, colors['ENDC'], ret) return msg
saltstack/salt
salt/output/highstate.py
_format_terse
python
def _format_terse(tcolor, comps, ret, colors, tabular): ''' Terse formatting of a message. ''' result = 'Clean' if ret['changes']: result = 'Changed' if ret['result'] is False: result = 'Failed' elif ret['result'] is None: result = 'Differs' if tabular is True: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}\n'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += '{0}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += '{6[start_time]!s} [{6[duration]!s:>7} ms] ' fmt_string += '{2:>10}.{3:<10} {4:7} Name: {1}{5}' elif isinstance(tabular, six.string_types): fmt_string = tabular else: fmt_string = '' if 'warnings' in ret: fmt_string += '{c[LIGHT_RED]}Warnings:\n{w}{c[ENDC]}'.format( c=colors, w='\n'.join(ret['warnings']) ) fmt_string += ' {0} Name: {1} - Function: {2}.{3} - Result: {4}' if __opts__.get('state_output_profile', True) and 'start_time' in ret: fmt_string += ' Started: - {6[start_time]!s} Duration: {6[duration]!s} ms' fmt_string += '{5}' msg = fmt_string.format(tcolor, comps[2], comps[0], comps[-1], result, colors['ENDC'], ret) return msg
Terse formatting of a message.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/highstate.py#L554-L595
null
# -*- coding: utf-8 -*- ''' Outputter for displaying results of state runs ============================================== The return data from the Highstate command is a standard data structure which is parsed by the highstate outputter to deliver a clean and readable set of information about the HighState run on minions. Two configurations can be set to modify the highstate outputter. These values can be set in the master config to change the output of the ``salt`` command or set in the minion config to change the output of the ``salt-call`` command. state_verbose By default `state_verbose` is set to `True`, setting this to `False` will instruct the highstate outputter to omit displaying anything in green, this means that nothing with a result of True and no changes will not be printed state_output: The highstate outputter has six output modes, ``full``, ``terse``, ``mixed``, ``changes`` and ``filter`` * The default is set to ``full``, which will display many lines of detailed information for each executed chunk. * If ``terse`` is used, then the output is greatly simplified and shown in only one line. * If ``mixed`` is used, then terse output will be used unless a state failed, in which case full output will be used. * If ``changes`` is used, then terse output will be used if there was no error and no changes, otherwise full output will be used. * If ``filter`` is used, then either or both of two different filters can be used: ``exclude`` or ``terse``. * for ``exclude``, state.highstate expects a list of states to be excluded (or ``None``) followed by ``True`` for terse output or ``False`` for regular output. Because of parsing nuances, if only one of these is used, it must still contain a comma. For instance: `exclude=True,`. * for ``terse``, state.highstate expects simply ``True`` or ``False``. These can be set as such from the command line, or in the Salt config as `state_output_exclude` or `state_output_terse`, respectively. The output modes have one modifier: ``full_id``, ``terse_id``, ``mixed_id``, ``changes_id`` and ``filter_id`` If ``_id`` is used, then the corresponding form will be used, but the value for ``name`` will be drawn from the state ID. This is useful for cases where the name value might be very long and hard to read. state_tabular: If `state_output` uses the terse output, set this to `True` for an aligned output format. If you wish to use a custom format, this can be set to a string. Example usage: If ``state_output: filter`` is set in the configuration file: .. code-block:: bash salt '*' state.highstate exclude=None,True means to exclude no states from the highstate and turn on terse output. .. code-block:: bash salt twd state.highstate exclude=problemstate1,problemstate2,False means to exclude states ``problemstate1`` and ``problemstate2`` from the highstate, and use regular output. Example output for the above highstate call when ``top.sls`` defines only one other state to apply to minion ``twd``: .. code-block:: text twd: Summary for twd ------------ Succeeded: 1 (changed=1) Failed: 0 ------------ Total states run: 1 Example output with no special settings in configuration files: .. code-block:: text myminion: ---------- ID: test.ping Function: module.run Result: True Comment: Module function test.ping executed Changes: ---------- ret: True Summary for myminion ------------ Succeeded: 1 Failed: 0 ------------ Total: 0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import pprint import re import textwrap # Import salt libs import salt.utils.color import salt.utils.data import salt.utils.stringutils import salt.output # Import 3rd-party libs from salt.ext import six import logging log = logging.getLogger(__name__) def output(data, **kwargs): # pylint: disable=unused-argument ''' The HighState Outputter is only meant to be used with the state.highstate function, or a function that returns highstate return data. ''' if len(data.keys()) == 1: # account for nested orchs via saltutil.runner if 'return' in data: data = data['return'] # account for envelope data if being passed lookup_jid ret if isinstance(data, dict): _data = next(iter(data.values())) if 'jid' in _data and 'fun' in _data: data = _data['return'] # output() is recursive, if we aren't passed a dict just return it if isinstance(data, int) or isinstance(data, six.string_types): return data # Discard retcode in dictionary as present in orchestrate data local_masters = [key for key in data.keys() if key.endswith('_master')] orchestrator_output = 'retcode' in data.keys() and len(local_masters) == 1 if orchestrator_output: del data['retcode'] # If additional information is passed through via the "data" dictionary to # the highstate outputter, such as "outputter" or "retcode", discard it. # We only want the state data that was passed through, if it is wrapped up # in the "data" key, as the orchestrate runner does. See Issue #31330, # pull request #27838, and pull request #27175 for more information. if 'data' in data: data = data.pop('data') indent_level = kwargs.get('indent_level', 1) ret = [ _format_host(host, hostdata, indent_level=indent_level)[0] for host, hostdata in six.iteritems(data) ] if ret: return "\n".join(ret) log.error( 'Data passed to highstate outputter is not a valid highstate return: %s', data ) # We should not reach here, but if we do return empty string return '' def _format_host(host, data, indent_level=1): ''' Main highstate formatter. can be called recursively if a nested highstate contains other highstates (ie in an orchestration) ''' host = salt.utils.data.decode(host) colors = salt.utils.color.get_colors( __opts__.get('color'), __opts__.get('color_theme')) tabular = __opts__.get('state_tabular', False) rcounts = {} rdurations = [] hcolor = colors['GREEN'] hstrs = [] nchanges = 0 strip_colors = __opts__.get('strip_colors', True) if isinstance(data, int) or isinstance(data, six.string_types): # Data in this format is from saltmod.function, # so it is always a 'change' nchanges = 1 hstrs.append(('{0} {1}{2[ENDC]}' .format(hcolor, data, colors))) hcolor = colors['CYAN'] # Print the minion name in cyan if isinstance(data, list): # Errors have been detected, list them in RED! hcolor = colors['LIGHT_RED'] hstrs.append((' {0}Data failed to compile:{1[ENDC]}' .format(hcolor, colors))) for err in data: if strip_colors: err = salt.output.strip_esc_sequence( salt.utils.data.decode(err) ) hstrs.append(('{0}----------\n {1}{2[ENDC]}' .format(hcolor, err, colors))) if isinstance(data, dict): # Verify that the needed data is present data_tmp = {} for tname, info in six.iteritems(data): if isinstance(info, dict) and tname is not 'changes' and info and '__run_num__' not in info: err = ('The State execution failed to record the order ' 'in which all states were executed. The state ' 'return missing data is:') hstrs.insert(0, pprint.pformat(info)) hstrs.insert(0, err) if isinstance(info, dict) and 'result' in info: data_tmp[tname] = info data = data_tmp # Everything rendered as it should display the output for tname in sorted( data, key=lambda k: data[k].get('__run_num__', 0)): ret = data[tname] # Increment result counts rcounts.setdefault(ret['result'], 0) rcounts[ret['result']] += 1 rduration = ret.get('duration', 0) try: rdurations.append(float(rduration)) except ValueError: rduration, _, _ = rduration.partition(' ms') try: rdurations.append(float(rduration)) except ValueError: log.error('Cannot parse a float from duration %s', ret.get('duration', 0)) tcolor = colors['GREEN'] if ret.get('name') in ['state.orch', 'state.orchestrate', 'state.sls']: nested = output(ret['changes']['return'], indent_level=indent_level+1) ctext = re.sub('^', ' ' * 14 * indent_level, '\n'+nested, flags=re.MULTILINE) schanged = True nchanges += 1 else: schanged, ctext = _format_changes(ret['changes']) nchanges += 1 if schanged else 0 # Skip this state if it was successful & diff output was requested if __opts__.get('state_output_diff', False) and \ ret['result'] and not schanged: continue # Skip this state if state_verbose is False, the result is True and # there were no changes made if not __opts__.get('state_verbose', False) and \ ret['result'] and not schanged: continue if schanged: tcolor = colors['CYAN'] if ret['result'] is False: hcolor = colors['RED'] tcolor = colors['RED'] if ret['result'] is None: hcolor = colors['LIGHT_YELLOW'] tcolor = colors['LIGHT_YELLOW'] state_output = __opts__.get('state_output', 'full').lower() comps = tname.split('_|-') if state_output.endswith('_id'): # Swap in the ID for the name. Refs #35137 comps[2] = comps[1] if state_output.startswith('filter'): # By default, full data is shown for all types. However, return # data may be excluded by setting state_output_exclude to a # comma-separated list of True, False or None, or including the # same list with the exclude option on the command line. For # now, this option must include a comma. For example: # exclude=True, # The same functionality is also available for making return # data terse, instead of excluding it. cliargs = __opts__.get('arg', []) clikwargs = {} for item in cliargs: if isinstance(item, dict) and '__kwarg__' in item: clikwargs = item.copy() exclude = clikwargs.get( 'exclude', __opts__.get('state_output_exclude', []) ) if isinstance(exclude, six.string_types): exclude = six.text_type(exclude).split(',') terse = clikwargs.get( 'terse', __opts__.get('state_output_terse', []) ) if isinstance(terse, six.string_types): terse = six.text_type(terse).split(',') if six.text_type(ret['result']) in terse: msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue if six.text_type(ret['result']) in exclude: continue elif any(( state_output.startswith('terse'), state_output.startswith('mixed') and ret['result'] is not False, # only non-error'd state_output.startswith('changes') and ret['result'] and not schanged # non-error'd non-changed )): # Print this chunk in a terse way and continue in the loop msg = _format_terse(tcolor, comps, ret, colors, tabular) hstrs.append(msg) continue state_lines = [ '{tcolor}----------{colors[ENDC]}', ' {tcolor} ID: {comps[1]}{colors[ENDC]}', ' {tcolor}Function: {comps[0]}.{comps[3]}{colors[ENDC]}', ' {tcolor} Result: {ret[result]!s}{colors[ENDC]}', ' {tcolor} Comment: {comment}{colors[ENDC]}', ] if __opts__.get('state_output_profile', True) and 'start_time' in ret: state_lines.extend([ ' {tcolor} Started: {ret[start_time]!s}{colors[ENDC]}', ' {tcolor}Duration: {ret[duration]!s}{colors[ENDC]}', ]) # This isn't the prettiest way of doing this, but it's readable. if comps[1] != comps[2]: state_lines.insert( 3, ' {tcolor} Name: {comps[2]}{colors[ENDC]}') # be sure that ret['comment'] is utf-8 friendly try: if not isinstance(ret['comment'], six.text_type): ret['comment'] = six.text_type(ret['comment']) except UnicodeDecodeError: # If we got here, we're on Python 2 and ret['comment'] somehow # contained a str type with unicode content. ret['comment'] = salt.utils.stringutils.to_unicode(ret['comment']) try: comment = salt.utils.data.decode(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) except AttributeError: # Assume comment is a list try: comment = ret['comment'].join(' ').replace( '\n', '\n' + ' ' * 13) except AttributeError: # Comment isn't a list either, just convert to string comment = six.text_type(ret['comment']) comment = comment.strip().replace( '\n', '\n' + ' ' * 14) # If there is a data attribute, append it to the comment if 'data' in ret: if isinstance(ret['data'], list): for item in ret['data']: comment = '{0} {1}'.format(comment, item) elif isinstance(ret['data'], dict): for key, value in ret['data'].items(): comment = '{0}\n\t\t{1}: {2}'.format(comment, key, value) else: comment = '{0} {1}'.format(comment, ret['data']) for detail in ['start_time', 'duration']: ret.setdefault(detail, '') if ret['duration'] != '': ret['duration'] = '{0} ms'.format(ret['duration']) svars = { 'tcolor': tcolor, 'comps': comps, 'ret': ret, 'comment': salt.utils.data.decode(comment), # This nukes any trailing \n and indents the others. 'colors': colors } hstrs.extend([sline.format(**svars) for sline in state_lines]) changes = ' Changes: ' + ctext hstrs.append(('{0}{1}{2[ENDC]}' .format(tcolor, changes, colors))) if 'warnings' in ret: rcounts.setdefault('warnings', 0) rcounts['warnings'] += 1 wrapper = textwrap.TextWrapper( width=80, initial_indent=' ' * 14, subsequent_indent=' ' * 14 ) hstrs.append( ' {colors[LIGHT_RED]} Warnings: {0}{colors[ENDC]}'.format( wrapper.fill('\n'.join(ret['warnings'])).lstrip(), colors=colors ) ) # Append result counts to end of output colorfmt = '{0}{1}{2[ENDC]}' rlabel = {True: 'Succeeded', False: 'Failed', None: 'Not Run', 'warnings': 'Warnings'} count_max_len = max([len(six.text_type(x)) for x in six.itervalues(rcounts)] or [0]) label_max_len = max([len(x) for x in six.itervalues(rlabel)] or [0]) line_max_len = label_max_len + count_max_len + 2 # +2 for ': ' hstrs.append( colorfmt.format( colors['CYAN'], '\nSummary for {0}\n{1}'.format(host, '-' * line_max_len), colors ) ) def _counts(label, count): return '{0}: {1:>{2}}'.format( label, count, line_max_len - (len(label) + 2) ) # Successful states changestats = [] if None in rcounts and rcounts.get(None, 0) > 0: # test=True states changestats.append( colorfmt.format( colors['LIGHT_YELLOW'], 'unchanged={0}'.format(rcounts.get(None, 0)), colors ) ) if nchanges > 0: changestats.append( colorfmt.format( colors['GREEN'], 'changed={0}'.format(nchanges), colors ) ) if changestats: changestats = ' ({0})'.format(', '.join(changestats)) else: changestats = '' hstrs.append( colorfmt.format( colors['GREEN'], _counts( rlabel[True], rcounts.get(True, 0) + rcounts.get(None, 0) ), colors ) + changestats ) # Failed states num_failed = rcounts.get(False, 0) hstrs.append( colorfmt.format( colors['RED'] if num_failed else colors['CYAN'], _counts(rlabel[False], num_failed), colors ) ) num_warnings = rcounts.get('warnings', 0) if num_warnings: hstrs.append( colorfmt.format( colors['LIGHT_RED'], _counts(rlabel['warnings'], num_warnings), colors ) ) totals = '{0}\nTotal states run: {1:>{2}}'.format('-' * line_max_len, sum(six.itervalues(rcounts)) - rcounts.get('warnings', 0), line_max_len - 7) hstrs.append(colorfmt.format(colors['CYAN'], totals, colors)) if __opts__.get('state_output_profile', True): sum_duration = sum(rdurations) duration_unit = 'ms' # convert to seconds if duration is 1000ms or more if sum_duration > 999: sum_duration /= 1000 duration_unit = 's' total_duration = 'Total run time: {0} {1}'.format( '{0:.3f}'.format(sum_duration).rjust(line_max_len - 5), duration_unit) hstrs.append(colorfmt.format(colors['CYAN'], total_duration, colors)) if strip_colors: host = salt.output.strip_esc_sequence(host) hstrs.insert(0, ('{0}{1}:{2[ENDC]}'.format(hcolor, host, colors))) return '\n'.join(hstrs), nchanges > 0 def _nested_changes(changes): ''' Print the changes data using the nested outputter ''' ret = '\n' ret += salt.output.out_format( changes, 'nested', __opts__, nested_indent=14) return ret def _format_changes(changes, orchestration=False): ''' Format the changes dict based on what the data is ''' if not changes: return False, '' if orchestration: return True, _nested_changes(changes) if not isinstance(changes, dict): return True, 'Invalid Changes data: {0}'.format(changes) ret = changes.get('ret') if ret is not None and changes.get('out') == 'highstate': ctext = '' changed = False for host, hostdata in six.iteritems(ret): s, c = _format_host(host, hostdata) ctext += '\n' + '\n'.join((' ' * 14 + l) for l in s.splitlines()) changed = changed or c else: changed = True ctext = _nested_changes(changes) return changed, ctext
saltstack/salt
salt/states/kernelpkg.py
mod_watch
python
def mod_watch(name, sfun, **kwargs): ''' The kernerpkg watcher, called to invoke the watch command. When called, execute a kernelpkg state based on a watch or listen call. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered. ''' if sfun in ('latest_active', 'latest_wait'): return latest_active(name, **kwargs) else: return {'name': name, 'changes': {}, 'comment': 'kernelpkg.{0} does not work with the watch ' 'requisite.'.format(sfun), 'result': False}
The kernerpkg watcher, called to invoke the watch command. When called, execute a kernelpkg state based on a watch or listen call. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kernelpkg.py#L204-L221
[ "def latest_active(name, at_time=None, **kwargs): # pylint: disable=unused-argument\n '''\n Initiate a reboot if the running kernel is not the latest one installed.\n\n .. note::\n\n This state does not install any patches. It only compares the running\n kernel version number to other kernel versions also installed in the\n system. If the running version is not the latest one installed, this\n state will reboot the system.\n\n See :py:func:`kernelpkg.upgrade <salt.modules.kernelpkg_linux_yum.upgrade>` and\n :py:func:`~salt.states.kernelpkg.latest_installed`\n for ways to install new kernel packages.\n\n This module does not attempt to understand or manage boot loader configurations\n it is possible to have a new kernel installed, but a boot loader configuration\n that will never activate it. For this reason, it would not be advisable to\n schedule this state to run automatically.\n\n Because this state function may cause the system to reboot, it may be preferable\n to move it to the very end of the state run.\n See :py:func:`~salt.states.kernelpkg.latest_wait`\n for a waitable state that can be called with the `listen` requesite.\n\n name\n Arbitrary name for the state. Does not affect behavior.\n\n at_time\n The wait time in minutes before the system will be rebooted.\n '''\n active = __salt__['kernelpkg.active']()\n latest = __salt__['kernelpkg.latest_installed']()\n ret = {'name': name}\n\n if __salt__['kernelpkg.needs_reboot']():\n\n ret['comment'] = ('The system will be booted to activate '\n 'kernel: {0}').format(latest)\n\n if __opts__['test']:\n ret['result'] = None\n ret['changes'] = {'kernel': {\n 'old': active,\n 'new': latest\n }}\n\n else:\n __salt__['system.reboot'](at_time=at_time)\n ret['result'] = True\n ret['changes'] = {'kernel': {\n 'old': active,\n 'new': latest\n }}\n\n else:\n ret['result'] = True\n ret['comment'] = ('The latest installed kernel package '\n 'is active: {0}').format(active)\n ret['changes'] = {}\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage kernel packages and active kernel version ========================================================================= Example state to install the latest kernel from package repositories: .. code-block:: yaml install-latest-kernel: kernel.latest_installed: [] Example state to boot the system if a new kernel has been installed: .. code-block:: yaml boot-latest-kernel: kernelpkg.latest_active: - at_time: 1 Example state chaining the install and reboot operations: .. code-block:: yaml install-latest-kernel: kernelpkg.latest_installed: [] boot-latest-kernel: kernelpkg.latest_active: - at_time: 1 - onchanges: - kernelpkg: install-latest-kernel Chaining can also be achieved using wait/listen requisites: .. code-block:: yaml install-latest-kernel: kernelpkg.latest_installed: [] boot-latest-kernel: kernelpkg.latest_wait: - at_time: 1 - listen: - kernelpkg: install-latest-kernel ''' from __future__ import absolute_import, print_function, unicode_literals import logging log = logging.getLogger(__name__) def __virtual__(): ''' Only make these states available if a kernelpkg provider has been detected or assigned for this minion ''' return 'kernelpkg.upgrade' in __salt__ def latest_installed(name, **kwargs): # pylint: disable=unused-argument ''' Ensure that the latest version of the kernel available in the repositories is installed. .. note:: This state only installs the kernel, but does not activate it. The new kernel should become active at the next reboot. See :py:func:`kernelpkg.needs_reboot <salt.modules.kernelpkg_linux_yum.needs_reboot>` for details on how to detect this condition, and :py:func:`~salt.states.kernelpkg.latest_active` to initiale a reboot when needed. name Arbitrary name for the state. Does not affect behavior. ''' installed = __salt__['kernelpkg.list_installed']() upgrade = __salt__['kernelpkg.latest_available']() ret = {'name': name} if upgrade in installed: ret['result'] = True ret['comment'] = ('The latest kernel package is already installed: ' '{0}').format(upgrade) ret['changes'] = {} else: if __opts__['test']: ret['result'] = None ret['changes'] = {} ret['comment'] = ('The latest kernel package will be installed: ' '{0}').format(upgrade) else: result = __salt__['kernelpkg.upgrade']() ret['result'] = True ret['changes'] = result['upgrades'] ret['comment'] = ('The latest kernel package has been installed, ' 'but not activated.') return ret def latest_active(name, at_time=None, **kwargs): # pylint: disable=unused-argument ''' Initiate a reboot if the running kernel is not the latest one installed. .. note:: This state does not install any patches. It only compares the running kernel version number to other kernel versions also installed in the system. If the running version is not the latest one installed, this state will reboot the system. See :py:func:`kernelpkg.upgrade <salt.modules.kernelpkg_linux_yum.upgrade>` and :py:func:`~salt.states.kernelpkg.latest_installed` for ways to install new kernel packages. This module does not attempt to understand or manage boot loader configurations it is possible to have a new kernel installed, but a boot loader configuration that will never activate it. For this reason, it would not be advisable to schedule this state to run automatically. Because this state function may cause the system to reboot, it may be preferable to move it to the very end of the state run. See :py:func:`~salt.states.kernelpkg.latest_wait` for a waitable state that can be called with the `listen` requesite. name Arbitrary name for the state. Does not affect behavior. at_time The wait time in minutes before the system will be rebooted. ''' active = __salt__['kernelpkg.active']() latest = __salt__['kernelpkg.latest_installed']() ret = {'name': name} if __salt__['kernelpkg.needs_reboot'](): ret['comment'] = ('The system will be booted to activate ' 'kernel: {0}').format(latest) if __opts__['test']: ret['result'] = None ret['changes'] = {'kernel': { 'old': active, 'new': latest }} else: __salt__['system.reboot'](at_time=at_time) ret['result'] = True ret['changes'] = {'kernel': { 'old': active, 'new': latest }} else: ret['result'] = True ret['comment'] = ('The latest installed kernel package ' 'is active: {0}').format(active) ret['changes'] = {} return ret def latest_wait(name, at_time=None, **kwargs): # pylint: disable=unused-argument ''' Initiate a reboot if the running kernel is not the latest one installed. This is the waitable version of :py:func:`~salt.states.kernelpkg.latest_active` and will not take any action unless triggered by a watch or listen requesite. .. note:: Because this state function may cause the system to reboot, it may be preferable to move it to the very end of the state run using `listen` or `listen_in` requisites. .. code-block:: yaml system-up-to-date: pkg.uptodate: - refresh: true boot-latest-kernel: kernelpkg.latest_wait: - at_time: 1 - listen: - pkg: system-up-to-date name Arbitrary name for the state. Does not affect behavior. at_time The wait time in minutes before the system will be rebooted. ''' return {'name': name, 'changes': {}, 'result': True, 'comment': ''}
saltstack/salt
salt/modules/solr.py
_get_none_or_value
python
def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None
PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L99-L122
null
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_get_return_dict
python
def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret
PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L138-L164
null
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_update_return_dict
python
def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret
PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L167-L194
null
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_format_url
python
def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra))
PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L197-L233
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_auth
python
def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) )
Install an auth handler for urllib2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L236-L255
null
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_http_request
python
def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)])
PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L258-L281
[ "def load(fp, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.load\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n return kwargs.pop('_json_module', json).load(fp, **kwargs)\n", "def _auth(url):\n '''\n Install an auth handler for urllib2\n '''\n user = __salt__['config.get']('solr.user', False)\n password = __salt__['config.get']('solr.passwd', False)\n realm = __salt__['config.get']('solr.auth_realm', 'Solr')\n\n if user and password:\n basic = _HTTPBasicAuthHandler()\n basic.add_password(\n realm=realm, uri=url, user=user, passwd=password\n )\n digest = _HTTPDigestAuthHandler()\n digest.add_password(\n realm=realm, uri=url, user=user, passwd=password\n )\n _install_opener(\n _build_opener(basic, digest)\n )\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_replication_request
python
def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url)
PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L284-L310
[ "def _http_request(url, request_timeout=None):\n '''\n PRIVATE METHOD\n Uses salt.utils.json.load to fetch the JSON results from the solr API.\n\n url : str\n a complete URL that can be passed to urllib.open\n request_timeout : int (None)\n The number of seconds before the timeout should fail. Leave blank/None\n to use the default. __opts__['solr.request_timeout']\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n _auth(url)\n try:\n\n request_timeout = __salt__['config.option']('solr.request_timeout')\n kwargs = {} if request_timeout is None else {'timeout': request_timeout}\n data = salt.utils.json.load(_urlopen(url, **kwargs))\n return _get_return_dict(True, data, [])\n except Exception as err:\n return _get_return_dict(False, {}, [\"{0} : {1}\".format(url, err)])\n", "def _format_url(handler, host=None, core_name=None, extra=None):\n '''\n PRIVATE METHOD\n Formats the URL based on parameters, and if cores are used or not\n\n handler : str\n The request handler to hit.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you\n are not using cores or if you want to check all cores.\n extra : list<str> ([])\n A list of name value pairs in string format. e.g. ['name=value']\n\n Return: str\n Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>)\n '''\n extra = [] if extra is None else extra\n if _get_none_or_value(host) is None or host == 'None':\n host = __salt__['config.option']('solr.host')\n port = __salt__['config.option']('solr.port')\n baseurl = __salt__['config.option']('solr.baseurl')\n if _get_none_or_value(core_name) is None:\n if not extra:\n return \"http://{0}:{1}{2}/{3}?wt=json\".format(\n host, port, baseurl, handler)\n else:\n return \"http://{0}:{1}{2}/{3}?wt=json&{4}\".format(\n host, port, baseurl, handler, \"&\".join(extra))\n else:\n if not extra:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json\".format(\n host, port, baseurl, core_name, handler)\n else:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json&{5}\".format(\n host, port, baseurl, core_name, handler, \"&\".join(extra))\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_get_admin_info
python
def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp
PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L313-L335
[ "def _http_request(url, request_timeout=None):\n '''\n PRIVATE METHOD\n Uses salt.utils.json.load to fetch the JSON results from the solr API.\n\n url : str\n a complete URL that can be passed to urllib.open\n request_timeout : int (None)\n The number of seconds before the timeout should fail. Leave blank/None\n to use the default. __opts__['solr.request_timeout']\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n _auth(url)\n try:\n\n request_timeout = __salt__['config.option']('solr.request_timeout')\n kwargs = {} if request_timeout is None else {'timeout': request_timeout}\n data = salt.utils.json.load(_urlopen(url, **kwargs))\n return _get_return_dict(True, data, [])\n except Exception as err:\n return _get_return_dict(False, {}, [\"{0} : {1}\".format(url, err)])\n", "def _format_url(handler, host=None, core_name=None, extra=None):\n '''\n PRIVATE METHOD\n Formats the URL based on parameters, and if cores are used or not\n\n handler : str\n The request handler to hit.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you\n are not using cores or if you want to check all cores.\n extra : list<str> ([])\n A list of name value pairs in string format. e.g. ['name=value']\n\n Return: str\n Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>)\n '''\n extra = [] if extra is None else extra\n if _get_none_or_value(host) is None or host == 'None':\n host = __salt__['config.option']('solr.host')\n port = __salt__['config.option']('solr.port')\n baseurl = __salt__['config.option']('solr.baseurl')\n if _get_none_or_value(core_name) is None:\n if not extra:\n return \"http://{0}:{1}{2}/{3}?wt=json\".format(\n host, port, baseurl, handler)\n else:\n return \"http://{0}:{1}{2}/{3}?wt=json&{4}\".format(\n host, port, baseurl, handler, \"&\".join(extra))\n else:\n if not extra:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json\".format(\n host, port, baseurl, core_name, handler)\n else:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json&{5}\".format(\n host, port, baseurl, core_name, handler, \"&\".join(extra))\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_merge_options
python
def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults
PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L350-L371
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_pre_index_check
python
def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp
PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L374-L419
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _is_master():\n '''\n PRIVATE METHOD\n Simple method to determine if the minion is configured as master or slave\n\n Return: boolean::\n\n True if __opts__['solr.type'] = master\n '''\n return __salt__['config.option']('solr.type') == 'master'\n", "def import_status(handler, host=None, core_name=None, verbose=False):\n '''\n Submits an import command to the specified handler using specified options.\n This command can only be run if the minion is configured with\n solr.type: 'master'\n\n handler : str\n The name of the data import handler.\n host : str (None)\n The solr host to query. __opts__['host'] is default.\n core : str (None)\n The core the handler belongs to.\n verbose : boolean (False)\n Specifies verbose output\n\n Return : dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' solr.import_status dataimport None music False\n '''\n if not _is_master() and _get_none_or_value(host) is None:\n errors = ['solr.import_status can only be called by \"master\" minions']\n return _get_return_dict(False, errors=errors)\n\n extra = [\"command=status\"]\n if verbose:\n extra.append(\"verbose=true\")\n url = _format_url(handler, host=host, core_name=core_name, extra=extra)\n return _http_request(url)\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
_find_value
python
def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret
PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L422-L456
null
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
lucene_version
python
def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp
Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L461-L501
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _update_return_dict(ret, success, data, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Updates the return dictionary and returns it.\n\n ret : dict<str,obj>\n The original return dict to update. The ret param should have\n been created from _get_return_dict()\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret['success'] = success\n ret['data'].update(data)\n ret['errors'] = ret['errors'] + errors\n ret['warnings'] = ret['warnings'] + warnings\n return ret\n", "def _get_admin_info(command, host=None, core_name=None):\n '''\n PRIVATE METHOD\n Calls the _http_request method and passes the admin command to execute\n and stores the data. This data is fairly static but should be refreshed\n periodically to make sure everything this OK. The data object will contain\n the JSON response.\n\n command : str\n The admin command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n url = _format_url(\"admin/{0}\".format(command), host, core_name=core_name)\n resp = _http_request(url)\n return resp\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
version
python
def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp
Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L504-L546
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _update_return_dict(ret, success, data, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Updates the return dictionary and returns it.\n\n ret : dict<str,obj>\n The original return dict to update. The ret param should have\n been created from _get_return_dict()\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret['success'] = success\n ret['data'].update(data)\n ret['errors'] = ret['errors'] + errors\n ret['warnings'] = ret['warnings'] + warnings\n return ret\n", "def _get_admin_info(command, host=None, core_name=None):\n '''\n PRIVATE METHOD\n Calls the _http_request method and passes the admin command to execute\n and stores the data. This data is fairly static but should be refreshed\n periodically to make sure everything this OK. The data object will contain\n the JSON response.\n\n command : str\n The admin command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n url = _format_url(\"admin/{0}\".format(command), host, core_name=core_name)\n resp = _http_request(url)\n return resp\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
optimize
python
def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url)
Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L549-L597
[ "def _http_request(url, request_timeout=None):\n '''\n PRIVATE METHOD\n Uses salt.utils.json.load to fetch the JSON results from the solr API.\n\n url : str\n a complete URL that can be passed to urllib.open\n request_timeout : int (None)\n The number of seconds before the timeout should fail. Leave blank/None\n to use the default. __opts__['solr.request_timeout']\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n _auth(url)\n try:\n\n request_timeout = __salt__['config.option']('solr.request_timeout')\n kwargs = {} if request_timeout is None else {'timeout': request_timeout}\n data = salt.utils.json.load(_urlopen(url, **kwargs))\n return _get_return_dict(True, data, [])\n except Exception as err:\n return _get_return_dict(False, {}, [\"{0} : {1}\".format(url, err)])\n", "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _update_return_dict(ret, success, data, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Updates the return dictionary and returns it.\n\n ret : dict<str,obj>\n The original return dict to update. The ret param should have\n been created from _get_return_dict()\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret['success'] = success\n ret['data'].update(data)\n ret['errors'] = ret['errors'] + errors\n ret['warnings'] = ret['warnings'] + warnings\n return ret\n", "def _format_url(handler, host=None, core_name=None, extra=None):\n '''\n PRIVATE METHOD\n Formats the URL based on parameters, and if cores are used or not\n\n handler : str\n The request handler to hit.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you\n are not using cores or if you want to check all cores.\n extra : list<str> ([])\n A list of name value pairs in string format. e.g. ['name=value']\n\n Return: str\n Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>)\n '''\n extra = [] if extra is None else extra\n if _get_none_or_value(host) is None or host == 'None':\n host = __salt__['config.option']('solr.host')\n port = __salt__['config.option']('solr.port')\n baseurl = __salt__['config.option']('solr.baseurl')\n if _get_none_or_value(core_name) is None:\n if not extra:\n return \"http://{0}:{1}{2}/{3}?wt=json\".format(\n host, port, baseurl, handler)\n else:\n return \"http://{0}:{1}{2}/{3}?wt=json&{4}\".format(\n host, port, baseurl, handler, \"&\".join(extra))\n else:\n if not extra:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json\".format(\n host, port, baseurl, core_name, handler)\n else:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json&{5}\".format(\n host, port, baseurl, core_name, handler, \"&\".join(extra))\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
ping
python
def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp
Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L600-L634
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _update_return_dict(ret, success, data, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Updates the return dictionary and returns it.\n\n ret : dict<str,obj>\n The original return dict to update. The ret param should have\n been created from _get_return_dict()\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret['success'] = success\n ret['data'].update(data)\n ret['errors'] = ret['errors'] + errors\n ret['warnings'] = ret['warnings'] + warnings\n return ret\n", "def _get_admin_info(command, host=None, core_name=None):\n '''\n PRIVATE METHOD\n Calls the _http_request method and passes the admin command to execute\n and stores the data. This data is fairly static but should be refreshed\n periodically to make sure everything this OK. The data object will contain\n the JSON response.\n\n command : str\n The admin command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n url = _format_url(\"admin/{0}\".format(command), host, core_name=core_name)\n resp = _http_request(url)\n return resp\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
is_replication_enabled
python
def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret
SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L637-L708
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _replication_request(command, host=None, core_name=None, params=None):\n '''\n PRIVATE METHOD\n Performs the requested replication command and returns a dictionary with\n success, errors and data as keys. The data object will contain the JSON\n response.\n\n command : str\n The replication command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n params : list<str> ([])\n Any additional parameters you want to send. Should be a lsit of\n strings in name=value format. e.g. ['name=value']\n\n Return: dict<str, obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n params = [] if params is None else params\n extra = [\"command={0}\".format(command)] + params\n url = _format_url('replication', host=host, core_name=core_name,\n extra=extra)\n return _http_request(url)\n", "def _is_master():\n '''\n PRIVATE METHOD\n Simple method to determine if the minion is configured as master or slave\n\n Return: boolean::\n\n True if __opts__['solr.type'] = master\n '''\n return __salt__['config.option']('solr.type') == 'master'\n", "def _checks(ret, success, resp, core):\n if response['success']:\n slave = resp['data']['details']['slave']\n # we need to initialize this to false in case there is an error\n # on the master and we can't get this info.\n enabled = 'false'\n master_url = slave['masterUrl']\n # check for errors on the slave\n if 'ERROR' in slave:\n success = False\n err = \"{0}: {1} - {2}\".format(core, slave['ERROR'], master_url)\n resp['errors'].append(err)\n # if there is an error return everything\n data = slave if core is None else {core: {'data': slave}}\n else:\n enabled = slave['masterDetails']['master'][\n 'replicationEnabled']\n # if replication is turned off on the master, or polling is\n # disabled we need to return false. These may not be errors,\n # but the purpose of this call is to check to see if the slaves\n # can replicate.\n if enabled == 'false':\n resp['warnings'].append(\"Replication is disabled on master.\")\n success = False\n if slave['isPollingDisabled'] == 'true':\n success = False\n resp['warning'].append(\"Polling is disabled\")\n # update the return\n ret = _update_return_dict(ret, success, data,\n resp['errors'], resp['warnings'])\n return (ret, success)\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
match_index_versions
python
def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret
SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L711-L800
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _replication_request(command, host=None, core_name=None, params=None):\n '''\n PRIVATE METHOD\n Performs the requested replication command and returns a dictionary with\n success, errors and data as keys. The data object will contain the JSON\n response.\n\n command : str\n The replication command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n params : list<str> ([])\n Any additional parameters you want to send. Should be a lsit of\n strings in name=value format. e.g. ['name=value']\n\n Return: dict<str, obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n params = [] if params is None else params\n extra = [\"command={0}\".format(command)] + params\n url = _format_url('replication', host=host, core_name=core_name,\n extra=extra)\n return _http_request(url)\n", "def _is_master():\n '''\n PRIVATE METHOD\n Simple method to determine if the minion is configured as master or slave\n\n Return: boolean::\n\n True if __opts__['solr.type'] = master\n '''\n return __salt__['config.option']('solr.type') == 'master'\n", "def _match(ret, success, resp, core):\n if response['success']:\n slave = resp['data']['details']['slave']\n master_url = resp['data']['details']['slave']['masterUrl']\n if 'ERROR' in slave:\n error = slave['ERROR']\n success = False\n err = \"{0}: {1} - {2}\".format(core, error, master_url)\n resp['errors'].append(err)\n # if there was an error return the entire response so the\n # alterer can get what it wants\n data = slave if core is None else {core: {'data': slave}}\n else:\n versions = {\n 'master': slave['masterDetails']['master'][\n 'replicatableIndexVersion'],\n 'slave': resp['data']['details']['indexVersion'],\n 'next_replication': slave['nextExecutionAt'],\n 'failed_list': []\n }\n if 'replicationFailedAtList' in slave:\n versions.update({'failed_list': slave[\n 'replicationFailedAtList']})\n # check the index versions\n if versions['master'] != versions['slave']:\n success = False\n resp['errors'].append(\n 'Master and Slave index versions do not match.'\n )\n data = versions if core is None else {core: {'data': versions}}\n ret = _update_return_dict(ret, success, data,\n resp['errors'], resp['warnings'])\n else:\n success = False\n err = resp['errors']\n data = resp['data']\n ret = _update_return_dict(ret, success, data, errors=err)\n return (ret, success)\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
replication_details
python
def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret
Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L803-L838
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _update_return_dict(ret, success, data, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Updates the return dictionary and returns it.\n\n ret : dict<str,obj>\n The original return dict to update. The ret param should have\n been created from _get_return_dict()\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret['success'] = success\n ret['data'].update(data)\n ret['errors'] = ret['errors'] + errors\n ret['warnings'] = ret['warnings'] + warnings\n return ret\n", "def _replication_request(command, host=None, core_name=None, params=None):\n '''\n PRIVATE METHOD\n Performs the requested replication command and returns a dictionary with\n success, errors and data as keys. The data object will contain the JSON\n response.\n\n command : str\n The replication command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n params : list<str> ([])\n Any additional parameters you want to send. Should be a lsit of\n strings in name=value format. e.g. ['name=value']\n\n Return: dict<str, obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n params = [] if params is None else params\n extra = [\"command={0}\".format(command)] + params\n url = _format_url('replication', host=host, core_name=core_name,\n extra=extra)\n return _http_request(url)\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
backup
python
def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp
Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L841-L899
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _update_return_dict(ret, success, data, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Updates the return dictionary and returns it.\n\n ret : dict<str,obj>\n The original return dict to update. The ret param should have\n been created from _get_return_dict()\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret['success'] = success\n ret['data'].update(data)\n ret['errors'] = ret['errors'] + errors\n ret['warnings'] = ret['warnings'] + warnings\n return ret\n", "def _replication_request(command, host=None, core_name=None, params=None):\n '''\n PRIVATE METHOD\n Performs the requested replication command and returns a dictionary with\n success, errors and data as keys. The data object will contain the JSON\n response.\n\n command : str\n The replication command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n params : list<str> ([])\n Any additional parameters you want to send. Should be a lsit of\n strings in name=value format. e.g. ['name=value']\n\n Return: dict<str, obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n params = [] if params is None else params\n extra = [\"command={0}\".format(command)] + params\n url = _format_url('replication', host=host, core_name=core_name,\n extra=extra)\n return _http_request(url)\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
set_is_polling
python
def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp
SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L902-L945
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _update_return_dict(ret, success, data, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Updates the return dictionary and returns it.\n\n ret : dict<str,obj>\n The original return dict to update. The ret param should have\n been created from _get_return_dict()\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret['success'] = success\n ret['data'].update(data)\n ret['errors'] = ret['errors'] + errors\n ret['warnings'] = ret['warnings'] + warnings\n return ret\n", "def _replication_request(command, host=None, core_name=None, params=None):\n '''\n PRIVATE METHOD\n Performs the requested replication command and returns a dictionary with\n success, errors and data as keys. The data object will contain the JSON\n response.\n\n command : str\n The replication command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n params : list<str> ([])\n Any additional parameters you want to send. Should be a lsit of\n strings in name=value format. e.g. ['name=value']\n\n Return: dict<str, obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n params = [] if params is None else params\n extra = [\"command={0}\".format(command)] + params\n url = _format_url('replication', host=host, core_name=core_name,\n extra=extra)\n return _http_request(url)\n", "def _is_master():\n '''\n PRIVATE METHOD\n Simple method to determine if the minion is configured as master or slave\n\n Return: boolean::\n\n True if __opts__['solr.type'] = master\n '''\n return __salt__['config.option']('solr.type') == 'master'\n", "def set_is_polling(polling, host=None, core_name=None):\n '''\n SLAVE CALL\n Prevent the slaves from polling the master for updates.\n\n polling : boolean\n True will enable polling. False will disable it.\n host : str (None)\n The solr host to query. __opts__['host'] is default.\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n\n Return : dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' solr.set_is_polling False\n '''\n\n ret = _get_return_dict()\n # since only slaves can call this let's check the config:\n if _is_master() and _get_none_or_value(host) is None:\n err = ['solr.set_is_polling can only be called by \"slave\" minions']\n return ret.update({'success': False, 'errors': err})\n\n cmd = \"enablepoll\" if polling else \"disapblepoll\"\n if _get_none_or_value(core_name) is None and _check_for_cores():\n success = True\n for name in __opts__['solr.cores']:\n resp = set_is_polling(cmd, host=host, core_name=name)\n if not resp['success']:\n success = False\n data = {name: {'data': resp['data']}}\n ret = _update_return_dict(ret, success, data,\n resp['errors'], resp['warnings'])\n return ret\n else:\n resp = _replication_request(cmd, host=host, core_name=core_name)\n return resp\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
set_replication_enabled
python
def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name)
MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L948-L993
[ "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _update_return_dict(ret, success, data, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Updates the return dictionary and returns it.\n\n ret : dict<str,obj>\n The original return dict to update. The ret param should have\n been created from _get_return_dict()\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret['success'] = success\n ret['data'].update(data)\n ret['errors'] = ret['errors'] + errors\n ret['warnings'] = ret['warnings'] + warnings\n return ret\n", "def _replication_request(command, host=None, core_name=None, params=None):\n '''\n PRIVATE METHOD\n Performs the requested replication command and returns a dictionary with\n success, errors and data as keys. The data object will contain the JSON\n response.\n\n command : str\n The replication command to execute.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name: str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n params : list<str> ([])\n Any additional parameters you want to send. Should be a lsit of\n strings in name=value format. e.g. ['name=value']\n\n Return: dict<str, obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n params = [] if params is None else params\n extra = [\"command={0}\".format(command)] + params\n url = _format_url('replication', host=host, core_name=core_name,\n extra=extra)\n return _http_request(url)\n", "def _is_master():\n '''\n PRIVATE METHOD\n Simple method to determine if the minion is configured as master or slave\n\n Return: boolean::\n\n True if __opts__['solr.type'] = master\n '''\n return __salt__['config.option']('solr.type') == 'master'\n", "def set_replication_enabled(status, host=None, core_name=None):\n '''\n MASTER ONLY\n Sets the master to ignore poll requests from the slaves. Useful when you\n don't want the slaves replicating during indexing or when clearing the\n index.\n\n status : boolean\n Sets the replication status to the specified state.\n host : str (None)\n The solr host to query. __opts__['host'] is default.\n\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to set the status on all cores.\n\n Return : dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' solr.set_replication_enabled false, None, music\n '''\n if not _is_master() and _get_none_or_value(host) is None:\n return _get_return_dict(False,\n errors=['Only minions configured as master can run this'])\n cmd = 'enablereplication' if status else 'disablereplication'\n if _get_none_or_value(core_name) is None and _check_for_cores():\n ret = _get_return_dict()\n success = True\n for name in __opts__['solr.cores']:\n resp = set_replication_enabled(status, host, name)\n if not resp['success']:\n success = False\n data = {name: {'data': resp['data']}}\n ret = _update_return_dict(ret, success, data,\n resp['errors'], resp['warnings'])\n return ret\n else:\n if status:\n return _replication_request(cmd, host=host, core_name=core_name)\n else:\n return _replication_request(cmd, host=host, core_name=core_name)\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
signal
python
def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False)
Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L996-L1022
null
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
reload_core
python
def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url)
MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L1025-L1069
[ "def _http_request(url, request_timeout=None):\n '''\n PRIVATE METHOD\n Uses salt.utils.json.load to fetch the JSON results from the solr API.\n\n url : str\n a complete URL that can be passed to urllib.open\n request_timeout : int (None)\n The number of seconds before the timeout should fail. Leave blank/None\n to use the default. __opts__['solr.request_timeout']\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n _auth(url)\n try:\n\n request_timeout = __salt__['config.option']('solr.request_timeout')\n kwargs = {} if request_timeout is None else {'timeout': request_timeout}\n data = salt.utils.json.load(_urlopen(url, **kwargs))\n return _get_return_dict(True, data, [])\n except Exception as err:\n return _get_return_dict(False, {}, [\"{0} : {1}\".format(url, err)])\n", "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _format_url(handler, host=None, core_name=None, extra=None):\n '''\n PRIVATE METHOD\n Formats the URL based on parameters, and if cores are used or not\n\n handler : str\n The request handler to hit.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you\n are not using cores or if you want to check all cores.\n extra : list<str> ([])\n A list of name value pairs in string format. e.g. ['name=value']\n\n Return: str\n Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>)\n '''\n extra = [] if extra is None else extra\n if _get_none_or_value(host) is None or host == 'None':\n host = __salt__['config.option']('solr.host')\n port = __salt__['config.option']('solr.port')\n baseurl = __salt__['config.option']('solr.baseurl')\n if _get_none_or_value(core_name) is None:\n if not extra:\n return \"http://{0}:{1}{2}/{3}?wt=json\".format(\n host, port, baseurl, handler)\n else:\n return \"http://{0}:{1}{2}/{3}?wt=json&{4}\".format(\n host, port, baseurl, handler, \"&\".join(extra))\n else:\n if not extra:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json\".format(\n host, port, baseurl, core_name, handler)\n else:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json&{5}\".format(\n host, port, baseurl, core_name, handler, \"&\".join(extra))\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
reload_import_config
python
def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url)
MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L1114-L1154
[ "def _http_request(url, request_timeout=None):\n '''\n PRIVATE METHOD\n Uses salt.utils.json.load to fetch the JSON results from the solr API.\n\n url : str\n a complete URL that can be passed to urllib.open\n request_timeout : int (None)\n The number of seconds before the timeout should fail. Leave blank/None\n to use the default. __opts__['solr.request_timeout']\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n _auth(url)\n try:\n\n request_timeout = __salt__['config.option']('solr.request_timeout')\n kwargs = {} if request_timeout is None else {'timeout': request_timeout}\n data = salt.utils.json.load(_urlopen(url, **kwargs))\n return _get_return_dict(True, data, [])\n except Exception as err:\n return _get_return_dict(False, {}, [\"{0} : {1}\".format(url, err)])\n", "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _format_url(handler, host=None, core_name=None, extra=None):\n '''\n PRIVATE METHOD\n Formats the URL based on parameters, and if cores are used or not\n\n handler : str\n The request handler to hit.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you\n are not using cores or if you want to check all cores.\n extra : list<str> ([])\n A list of name value pairs in string format. e.g. ['name=value']\n\n Return: str\n Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>)\n '''\n extra = [] if extra is None else extra\n if _get_none_or_value(host) is None or host == 'None':\n host = __salt__['config.option']('solr.host')\n port = __salt__['config.option']('solr.port')\n baseurl = __salt__['config.option']('solr.baseurl')\n if _get_none_or_value(core_name) is None:\n if not extra:\n return \"http://{0}:{1}{2}/{3}?wt=json\".format(\n host, port, baseurl, handler)\n else:\n return \"http://{0}:{1}{2}/{3}?wt=json&{4}\".format(\n host, port, baseurl, handler, \"&\".join(extra))\n else:\n if not extra:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json\".format(\n host, port, baseurl, core_name, handler)\n else:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json&{5}\".format(\n host, port, baseurl, core_name, handler, \"&\".join(extra))\n", "def _is_master():\n '''\n PRIVATE METHOD\n Simple method to determine if the minion is configured as master or slave\n\n Return: boolean::\n\n True if __opts__['solr.type'] = master\n '''\n return __salt__['config.option']('solr.type') == 'master'\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
full_import
python
def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url)
MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L1198-L1252
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _http_request(url, request_timeout=None):\n '''\n PRIVATE METHOD\n Uses salt.utils.json.load to fetch the JSON results from the solr API.\n\n url : str\n a complete URL that can be passed to urllib.open\n request_timeout : int (None)\n The number of seconds before the timeout should fail. Leave blank/None\n to use the default. __opts__['solr.request_timeout']\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n _auth(url)\n try:\n\n request_timeout = __salt__['config.option']('solr.request_timeout')\n kwargs = {} if request_timeout is None else {'timeout': request_timeout}\n data = salt.utils.json.load(_urlopen(url, **kwargs))\n return _get_return_dict(True, data, [])\n except Exception as err:\n return _get_return_dict(False, {}, [\"{0} : {1}\".format(url, err)])\n", "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _check_for_cores():\n '''\n PRIVATE METHOD\n Checks to see if using_cores has been set or not. if it's been set\n return it, otherwise figure it out and set it. Then return it\n\n Return: boolean\n\n True if one or more cores defined in __opts__['solr.cores']\n '''\n return len(__salt__['config.option']('solr.cores')) > 0\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _format_url(handler, host=None, core_name=None, extra=None):\n '''\n PRIVATE METHOD\n Formats the URL based on parameters, and if cores are used or not\n\n handler : str\n The request handler to hit.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you\n are not using cores or if you want to check all cores.\n extra : list<str> ([])\n A list of name value pairs in string format. e.g. ['name=value']\n\n Return: str\n Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>)\n '''\n extra = [] if extra is None else extra\n if _get_none_or_value(host) is None or host == 'None':\n host = __salt__['config.option']('solr.host')\n port = __salt__['config.option']('solr.port')\n baseurl = __salt__['config.option']('solr.baseurl')\n if _get_none_or_value(core_name) is None:\n if not extra:\n return \"http://{0}:{1}{2}/{3}?wt=json\".format(\n host, port, baseurl, handler)\n else:\n return \"http://{0}:{1}{2}/{3}?wt=json&{4}\".format(\n host, port, baseurl, handler, \"&\".join(extra))\n else:\n if not extra:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json\".format(\n host, port, baseurl, core_name, handler)\n else:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json&{5}\".format(\n host, port, baseurl, core_name, handler, \"&\".join(extra))\n", "def _is_master():\n '''\n PRIVATE METHOD\n Simple method to determine if the minion is configured as master or slave\n\n Return: boolean::\n\n True if __opts__['solr.type'] = master\n '''\n return __salt__['config.option']('solr.type') == 'master'\n", "def _merge_options(options):\n '''\n PRIVATE METHOD\n updates the default import options from __opts__['solr.dih.import_options']\n with the dictionary passed in. Also converts booleans to strings\n to pass to solr.\n\n options : dict<str,boolean>\n Dictionary the over rides the default options defined in\n __opts__['solr.dih.import_options']\n\n Return: dict<str,boolean>::\n\n {option:boolean}\n '''\n defaults = __salt__['config.option']('solr.dih.import_options')\n if isinstance(options, dict):\n defaults.update(options)\n for key, val in six.iteritems(defaults):\n if isinstance(val, bool):\n defaults[key] = six.text_type(val).lower()\n return defaults\n", "def _pre_index_check(handler, host=None, core_name=None):\n '''\n PRIVATE METHOD - MASTER CALL\n Does a pre-check to make sure that all the options are set and that\n we can talk to solr before trying to send a command to solr. This\n Command should only be issued to masters.\n\n handler : str\n The import handler to check the state of\n host : str (None):\n The solr host to query. __opts__['host'] is default\n core_name (None):\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to check all cores.\n REQUIRED if you are using cores.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n # make sure that it's a master minion\n if _get_none_or_value(host) is None and not _is_master():\n err = [\n 'solr.pre_indexing_check can only be called by \"master\" minions']\n return _get_return_dict(False, err)\n # solr can run out of memory quickly if the dih is processing multiple\n # handlers at the same time, so if it's a multicore setup require a\n # core_name param.\n if _get_none_or_value(core_name) is None and _check_for_cores():\n errors = ['solr.full_import is not safe to multiple handlers at once']\n return _get_return_dict(False, errors=errors)\n # check to make sure that we're not already indexing\n resp = import_status(handler, host, core_name)\n if resp['success']:\n status = resp['data']['status']\n if status == 'busy':\n warn = ['An indexing process is already running.']\n return _get_return_dict(True, warnings=warn)\n if status != 'idle':\n errors = ['Unknown status: \"{0}\"'.format(status)]\n return _get_return_dict(False, data=resp['data'], errors=errors)\n else:\n errors = ['Status check failed. Response details: {0}'.format(resp)]\n return _get_return_dict(False, data=resp['data'], errors=errors)\n\n return resp\n", "def set_replication_enabled(status, host=None, core_name=None):\n '''\n MASTER ONLY\n Sets the master to ignore poll requests from the slaves. Useful when you\n don't want the slaves replicating during indexing or when clearing the\n index.\n\n status : boolean\n Sets the replication status to the specified state.\n host : str (None)\n The solr host to query. __opts__['host'] is default.\n\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you are\n not using cores or if you want to set the status on all cores.\n\n Return : dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' solr.set_replication_enabled false, None, music\n '''\n if not _is_master() and _get_none_or_value(host) is None:\n return _get_return_dict(False,\n errors=['Only minions configured as master can run this'])\n cmd = 'enablereplication' if status else 'disablereplication'\n if _get_none_or_value(core_name) is None and _check_for_cores():\n ret = _get_return_dict()\n success = True\n for name in __opts__['solr.cores']:\n resp = set_replication_enabled(status, host, name)\n if not resp['success']:\n success = False\n data = {name: {'data': resp['data']}}\n ret = _update_return_dict(ret, success, data,\n resp['errors'], resp['warnings'])\n return ret\n else:\n if status:\n return _replication_request(cmd, host=host, core_name=core_name)\n else:\n return _replication_request(cmd, host=host, core_name=core_name)\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
saltstack/salt
salt/modules/solr.py
import_status
python
def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False ''' if not _is_master() and _get_none_or_value(host) is None: errors = ['solr.import_status can only be called by "master" minions'] return _get_return_dict(False, errors=errors) extra = ["command=status"] if verbose: extra.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=extra) return _http_request(url)
Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Specifies verbose output Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.import_status dataimport None music False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L1309-L1342
[ "def _http_request(url, request_timeout=None):\n '''\n PRIVATE METHOD\n Uses salt.utils.json.load to fetch the JSON results from the solr API.\n\n url : str\n a complete URL that can be passed to urllib.open\n request_timeout : int (None)\n The number of seconds before the timeout should fail. Leave blank/None\n to use the default. __opts__['solr.request_timeout']\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n _auth(url)\n try:\n\n request_timeout = __salt__['config.option']('solr.request_timeout')\n kwargs = {} if request_timeout is None else {'timeout': request_timeout}\n data = salt.utils.json.load(_urlopen(url, **kwargs))\n return _get_return_dict(True, data, [])\n except Exception as err:\n return _get_return_dict(False, {}, [\"{0} : {1}\".format(url, err)])\n", "def _get_none_or_value(value):\n '''\n PRIVATE METHOD\n Checks to see if the value of a primitive or built-in container such as\n a list, dict, set, tuple etc is empty or none. None type is returned if the\n value is empty/None/False. Number data types that are 0 will return None.\n\n value : obj\n The primitive or built-in container to evaluate.\n\n Return: None or value\n '''\n if value is None:\n return None\n elif not value:\n return value\n # if it's a string, and it's not empty check for none\n elif isinstance(value, six.string_types):\n if value.lower() == 'none':\n return None\n return value\n # return None\n else:\n return None\n", "def _get_return_dict(success=True, data=None, errors=None, warnings=None):\n '''\n PRIVATE METHOD\n Creates a new return dict with default values. Defaults may be overwritten.\n\n success : boolean (True)\n True indicates a successful result.\n data : dict<str,obj> ({})\n Data to be returned to the caller.\n errors : list<str> ([()])\n A list of error messages to be returned to the caller\n warnings : list<str> ([])\n A list of warnings to be returned to the caller.\n\n Return: dict<str,obj>::\n\n {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n '''\n data = {} if data is None else data\n errors = [] if errors is None else errors\n warnings = [] if warnings is None else warnings\n ret = {'success': success,\n 'data': data,\n 'errors': errors,\n 'warnings': warnings}\n\n return ret\n", "def _format_url(handler, host=None, core_name=None, extra=None):\n '''\n PRIVATE METHOD\n Formats the URL based on parameters, and if cores are used or not\n\n handler : str\n The request handler to hit.\n host : str (None)\n The solr host to query. __opts__['host'] is default\n core_name : str (None)\n The name of the solr core if using cores. Leave this blank if you\n are not using cores or if you want to check all cores.\n extra : list<str> ([])\n A list of name value pairs in string format. e.g. ['name=value']\n\n Return: str\n Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>)\n '''\n extra = [] if extra is None else extra\n if _get_none_or_value(host) is None or host == 'None':\n host = __salt__['config.option']('solr.host')\n port = __salt__['config.option']('solr.port')\n baseurl = __salt__['config.option']('solr.baseurl')\n if _get_none_or_value(core_name) is None:\n if not extra:\n return \"http://{0}:{1}{2}/{3}?wt=json\".format(\n host, port, baseurl, handler)\n else:\n return \"http://{0}:{1}{2}/{3}?wt=json&{4}\".format(\n host, port, baseurl, handler, \"&\".join(extra))\n else:\n if not extra:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json\".format(\n host, port, baseurl, core_name, handler)\n else:\n return \"http://{0}:{1}{2}/{3}/{4}?wt=json&{5}\".format(\n host, port, baseurl, core_name, handler, \"&\".join(extra))\n", "def _is_master():\n '''\n PRIVATE METHOD\n Simple method to determine if the minion is configured as master or slave\n\n Return: boolean::\n\n True if __opts__['solr.type'] = master\n '''\n return __salt__['config.option']('solr.type') == 'master'\n" ]
# -*- coding: utf-8 -*- ''' Apache Solr Salt Module Author: Jed Glazner Version: 0.2.1 Modified: 12/09/2011 This module uses HTTP requests to talk to the apache solr request handlers to gather information and report errors. Because of this the minion doesn't necessarily need to reside on the actual slave. However if you want to use the signal function the minion must reside on the physical solr host. This module supports multi-core and standard setups. Certain methods are master/slave specific. Make sure you set the solr.type. If you have questions or want a feature request please ask. Coming Features in 0.3 ---------------------- 1. Add command for checking for replication failures on slaves 2. Improve match_index_versions since it's pointless on busy solr masters 3. Add additional local fs checks for backups to make sure they succeeded Override these in the minion config ----------------------------------- solr.cores A list of core names e.g. ['core1','core2']. An empty list indicates non-multicore setup. solr.baseurl The root level URL to access solr via HTTP solr.request_timeout The number of seconds before timing out an HTTP/HTTPS/FTP request. If nothing is specified then the python global timeout setting is used. solr.type Possible values are 'master' or 'slave' solr.backup_path The path to store your backups. If you are using cores and you can specify to append the core name to the path in the backup method. solr.num_backups For versions of solr >= 3.5. Indicates the number of backups to keep. This option is ignored if your version is less. solr.init_script The full path to your init script with start/stop options solr.dih.options A list of options to pass to the DIH. Required Options for DIH ------------------------ clean : False Clear the index before importing commit : True Commit the documents to the index upon completion optimize : True Optimize the index after commit is complete verbose : True Get verbose output ''' # Import python Libs from __future__ import absolute_import, unicode_literals, print_function import os # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext import six from salt.ext.six.moves.urllib.request import ( urlopen as _urlopen, HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=no-name-in-module,import-error # Import salt libs import salt.utils.json import salt.utils.path # ######################### PRIVATE METHODS ############################## def __virtual__(): ''' PRIVATE METHOD Solr needs to be installed to use this. Return: str/bool ''' if salt.utils.path.which('solr'): return 'solr' if salt.utils.path.which('apache-solr'): return 'solr' return (False, 'The solr execution module failed to load: requires both the solr and apache-solr binaries in the path.') def _get_none_or_value(value): ''' PRIVATE METHOD Checks to see if the value of a primitive or built-in container such as a list, dict, set, tuple etc is empty or none. None type is returned if the value is empty/None/False. Number data types that are 0 will return None. value : obj The primitive or built-in container to evaluate. Return: None or value ''' if value is None: return None elif not value: return value # if it's a string, and it's not empty check for none elif isinstance(value, six.string_types): if value.lower() == 'none': return None return value # return None else: return None def _check_for_cores(): ''' PRIVATE METHOD Checks to see if using_cores has been set or not. if it's been set return it, otherwise figure it out and set it. Then return it Return: boolean True if one or more cores defined in __opts__['solr.cores'] ''' return len(__salt__['config.option']('solr.cores')) > 0 def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' data = {} if data is None else data errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret = {'success': success, 'data': data, 'errors': errors, 'warnings': warnings} return ret def _update_return_dict(ret, success, data, errors=None, warnings=None): ''' PRIVATE METHOD Updates the return dictionary and returns it. ret : dict<str,obj> The original return dict to update. The ret param should have been created from _get_return_dict() success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the caller. errors : list<str> ([()]) A list of error messages to be returned to the caller warnings : list<str> ([]) A list of warnings to be returned to the caller. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' errors = [] if errors is None else errors warnings = [] if warnings is None else warnings ret['success'] = success ret['data'].update(data) ret['errors'] = ret['errors'] + errors ret['warnings'] = ret['warnings'] + warnings return ret def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. extra : list<str> ([]) A list of name value pairs in string format. e.g. ['name=value'] Return: str Fully formatted URL (http://<host>:<port>/solr/<handler>?wt=json&<extra>) ''' extra = [] if extra is None else extra if _get_none_or_value(host) is None or host == 'None': host = __salt__['config.option']('solr.host') port = __salt__['config.option']('solr.port') baseurl = __salt__['config.option']('solr.baseurl') if _get_none_or_value(core_name) is None: if not extra: return "http://{0}:{1}{2}/{3}?wt=json".format( host, port, baseurl, handler) else: return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( host, port, baseurl, handler, "&".join(extra)) else: if not extra: return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( host, port, baseurl, core_name, handler) else: return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( host, port, baseurl, core_name, handler, "&".join(extra)) def _auth(url): ''' Install an auth handler for urllib2 ''' user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) ) def _http_request(url, request_timeout=None): ''' PRIVATE METHOD Uses salt.utils.json.load to fetch the JSON results from the solr API. url : str a complete URL that can be passed to urllib.open request_timeout : int (None) The number of seconds before the timeout should fail. Leave blank/None to use the default. __opts__['solr.request_timeout'] Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' _auth(url) try: request_timeout = __salt__['config.option']('solr.request_timeout') kwargs = {} if request_timeout is None else {'timeout': request_timeout} data = salt.utils.json.load(_urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): ''' PRIVATE METHOD Performs the requested replication command and returns a dictionary with success, errors and data as keys. The data object will contain the JSON response. command : str The replication command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. params : list<str> ([]) Any additional parameters you want to send. Should be a lsit of strings in name=value format. e.g. ['name=value'] Return: dict<str, obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' params = [] if params is None else params extra = ["command={0}".format(command)] + params url = _format_url('replication', host=host, core_name=core_name, extra=extra) return _http_request(url) def _get_admin_info(command, host=None, core_name=None): ''' PRIVATE METHOD Calls the _http_request method and passes the admin command to execute and stores the data. This data is fairly static but should be refreshed periodically to make sure everything this OK. The data object will contain the JSON response. command : str The admin command to execute. host : str (None) The solr host to query. __opts__['host'] is default core_name: str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' url = _format_url("admin/{0}".format(command), host, core_name=core_name) resp = _http_request(url) return resp def _is_master(): ''' PRIVATE METHOD Simple method to determine if the minion is configured as master or slave Return: boolean:: True if __opts__['solr.type'] = master ''' return __salt__['config.option']('solr.type') == 'master' def _merge_options(options): ''' PRIVATE METHOD updates the default import options from __opts__['solr.dih.import_options'] with the dictionary passed in. Also converts booleans to strings to pass to solr. options : dict<str,boolean> Dictionary the over rides the default options defined in __opts__['solr.dih.import_options'] Return: dict<str,boolean>:: {option:boolean} ''' defaults = __salt__['config.option']('solr.dih.import_options') if isinstance(options, dict): defaults.update(options) for key, val in six.iteritems(defaults): if isinstance(val, bool): defaults[key] = six.text_type(val).lower() return defaults def _pre_index_check(handler, host=None, core_name=None): ''' PRIVATE METHOD - MASTER CALL Does a pre-check to make sure that all the options are set and that we can talk to solr before trying to send a command to solr. This Command should only be issued to masters. handler : str The import handler to check the state of host : str (None): The solr host to query. __opts__['host'] is default core_name (None): The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. REQUIRED if you are using cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} ''' # make sure that it's a master minion if _get_none_or_value(host) is None and not _is_master(): err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) # solr can run out of memory quickly if the dih is processing multiple # handlers at the same time, so if it's a multicore setup require a # core_name param. if _get_none_or_value(core_name) is None and _check_for_cores(): errors = ['solr.full_import is not safe to multiple handlers at once'] return _get_return_dict(False, errors=errors) # check to make sure that we're not already indexing resp = import_status(handler, host, core_name) if resp['success']: status = resp['data']['status'] if status == 'busy': warn = ['An indexing process is already running.'] return _get_return_dict(True, warnings=warn) if status != 'idle': errors = ['Unknown status: "{0}"'.format(status)] return _get_return_dict(False, data=resp['data'], errors=errors) else: errors = ['Status check failed. Response details: {0}'.format(resp)] return _get_return_dict(False, data=resp['data'], errors=errors) return resp def _find_value(ret_dict, key, path=None): ''' PRIVATE METHOD Traverses a dictionary of dictionaries/lists to find key and return the value stored. TODO:// this method doesn't really work very well, and it's not really very useful in its current state. The purpose for this method is to simplify parsing the JSON output so you can just pass the key you want to find and have it return the value. ret : dict<str,obj> The dictionary to search through. Typically this will be a dict returned from solr. key : str The key (str) to find in the dictionary Return: list<dict<str,obj>>:: [{path:path, value:value}] ''' if path is None: path = key else: path = "{0}:{1}".format(path, key) ret = [] for ikey, val in six.iteritems(ret_dict): if ikey == key: ret.append({path: val}) if isinstance(val, list): for item in val: if isinstance(item, dict): ret = ret + _find_value(item, key, path) if isinstance(val, dict): ret = ret + _find_value(val, key, path) return ret # ######################### PUBLIC METHODS ############################## def lucene_version(core_name=None): ''' Gets the lucene version that solr is using. If you are running a multi-core setup you should specify a core name since all the cores run under the same servlet container, they will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return: dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.lucene_version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): resp = _get_admin_info('system', core_name=name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] data = {name: {'lucene_version': version_num}} else: # generally this means that an exception happened. data = {name: {'lucene_version': None}} success = False ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['lucene-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors']) else: return resp def version(core_name=None): ''' Gets the solr version for the core specified. You should specify a core here as all the cores will run under the same servlet container and so will all have the same version. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.version ''' ret = _get_return_dict() # do we want to check for all the cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('system', core_name=name) if resp['success']: lucene = resp['data']['lucene'] data = {name: {'version': lucene['solr-spec-version']}} else: success = False data = {name: {'version': None}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _get_admin_info('system', core_name=core_name) if resp['success']: version_num = resp['data']['lucene']['solr-spec-version'] return _get_return_dict(True, {'version': version_num}, resp['errors'], resp['warnings']) else: return resp def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if you are going to run this on a slave be aware than search performance will be horrible while this command is being run. Additionally it can take a LONG time to run and your HTTP request may timeout. If that happens adjust your timeout settings. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.optimize music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __salt__['config.option']('solr.cores'): url = _format_url('update', host=host, core_name=name, extra=["optimize=true"]) resp = _http_request(url) if resp['success']: data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: url = _format_url('update', host=host, core_name=core_name, extra=["optimize=true"]) return _http_request(url) def ping(host=None, core_name=None): ''' Does a health check on solr, makes sure solr can talk to the indexes. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.ping music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = _get_admin_info('ping', host=host, core_name=name) if resp['success']: data = {name: {'status': resp['data']['status']}} else: success = False data = {name: {'status': None}} ret = _update_return_dict(ret, success, data, resp['errors']) return ret else: resp = _get_admin_info('ping', host=host, core_name=core_name) return resp def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.is_replication_enabled music ''' ret = _get_return_dict() success = True # since only slaves can call this let's check the config: if _is_master() and host is None: errors = ['Only "slave" minions can run "is_replication_enabled"'] return ret.update({'success': False, 'errors': errors}) # define a convenience method so we don't duplicate code def _checks(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] # we need to initialize this to false in case there is an error # on the master and we can't get this info. enabled = 'false' master_url = slave['masterUrl'] # check for errors on the slave if 'ERROR' in slave: success = False err = "{0}: {1} - {2}".format(core, slave['ERROR'], master_url) resp['errors'].append(err) # if there is an error return everything data = slave if core is None else {core: {'data': slave}} else: enabled = slave['masterDetails']['master'][ 'replicationEnabled'] # if replication is turned off on the master, or polling is # disabled we need to return false. These may not be errors, # but the purpose of this call is to check to see if the slaves # can replicate. if enabled == 'false': resp['warnings'].append("Replication is disabled on master.") success = False if slave['isPollingDisabled'] == 'true': success = False resp['warning'].append("Polling is disabled") # update the return ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return (ret, success) if _get_none_or_value(core_name) is None and _check_for_cores(): for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _checks(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _checks(ret, success, response, core_name) return ret def match_index_versions(host=None, core_name=None): ''' SLAVE CALL Verifies that the master and the slave versions are in sync by comparing the index version. If you are constantly pushing updates the index the master and slave versions will seldom match. A solution to this is pause indexing every so often to allow the slave to replicate and then call this method before allowing indexing to resume. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.match_index_versions music ''' # since only slaves can call this let's check the config: ret = _get_return_dict() success = True if _is_master() and _get_none_or_value(host) is None: return ret.update({ 'success': False, 'errors': [ 'solr.match_index_versions can only be called by ' '"slave" minions' ] }) # get the default return dict def _match(ret, success, resp, core): if response['success']: slave = resp['data']['details']['slave'] master_url = resp['data']['details']['slave']['masterUrl'] if 'ERROR' in slave: error = slave['ERROR'] success = False err = "{0}: {1} - {2}".format(core, error, master_url) resp['errors'].append(err) # if there was an error return the entire response so the # alterer can get what it wants data = slave if core is None else {core: {'data': slave}} else: versions = { 'master': slave['masterDetails']['master'][ 'replicatableIndexVersion'], 'slave': resp['data']['details']['indexVersion'], 'next_replication': slave['nextExecutionAt'], 'failed_list': [] } if 'replicationFailedAtList' in slave: versions.update({'failed_list': slave[ 'replicationFailedAtList']}) # check the index versions if versions['master'] != versions['slave']: success = False resp['errors'].append( 'Master and Slave index versions do not match.' ) data = versions if core is None else {core: {'data': versions}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: success = False err = resp['errors'] data = resp['data'] ret = _update_return_dict(ret, success, data, errors=err) return (ret, success) # check all cores? if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: response = _replication_request('details', host=host, core_name=name) ret, success = _match(ret, success, response, name) else: response = _replication_request('details', host=host, core_name=core_name) ret, success = _match(ret, success, response, core_name) return ret def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.replication_details music ''' ret = _get_return_dict() if _get_none_or_value(core_name) is None: success = True for name in __opts__['solr.cores']: resp = _replication_request('details', host=host, core_name=name) data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) else: resp = _replication_request('details', host=host, core_name=core_name) if resp['success']: ret = _update_return_dict(ret, resp['success'], resp['data'], resp['errors'], resp['warnings']) else: return resp return ret def backup(host=None, core_name=None, append_core_to_path=False): ''' Tell solr make a backup. This method can be mis-leading since it uses the backup API. If an error happens during the backup you are not notified. The status: 'OK' in the response simply means that solr received the request successfully. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. append_core_to_path : boolean (False) If True add the name of the core to the backup path. Assumes that minion backup path is not None. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.backup music ''' path = __opts__['solr.backup_path'] num_backups = __opts__['solr.num_backups'] if path is not None: if not path.endswith(os.path.sep): path += os.path.sep ret = _get_return_dict() if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: params = [] if path is not None: path = path + name if append_core_to_path else path params.append("&location={0}".format(path + name)) params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=name, params=params) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if core_name is not None and path is not None: if append_core_to_path: path += core_name if path is not None: params = ["location={0}".format(path)] params.append("&numberToKeep={0}".format(num_backups)) resp = _replication_request('backup', host=host, core_name=core_name, params=params) return resp def set_is_polling(polling, host=None, core_name=None): ''' SLAVE CALL Prevent the slaves from polling the master for updates. polling : boolean True will enable polling. False will disable it. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_is_polling False ''' ret = _get_return_dict() # since only slaves can call this let's check the config: if _is_master() and _get_none_or_value(host) is None: err = ['solr.set_is_polling can only be called by "slave" minions'] return ret.update({'success': False, 'errors': err}) cmd = "enablepoll" if polling else "disapblepoll" if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = set_is_polling(cmd, host=host, core_name=name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: resp = _replication_request(cmd, host=host, core_name=core_name) return resp def set_replication_enabled(status, host=None, core_name=None): ''' MASTER ONLY Sets the master to ignore poll requests from the slaves. Useful when you don't want the slaves replicating during indexing or when clearing the index. status : boolean Sets the replication status to the specified state. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to set the status on all cores. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.set_replication_enabled false, None, music ''' if not _is_master() and _get_none_or_value(host) is None: return _get_return_dict(False, errors=['Only minions configured as master can run this']) cmd = 'enablereplication' if status else 'disablereplication' if _get_none_or_value(core_name) is None and _check_for_cores(): ret = _get_return_dict() success = True for name in __opts__['solr.cores']: resp = set_replication_enabled(status, host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret else: if status: return _replication_request(cmd, host=host, core_name=core_name) else: return _replication_request(cmd, host=host, core_name=core_name) def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', 'stop', and 'restart' CLI Example: .. code-block:: bash salt '*' solr.signal restart ''' valid_signals = ('start', 'stop', 'restart') # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: msg = valid_signals[:-1] + ('or {0}'.format(valid_signals[-1]),) return '{0} is an invalid signal. Try: one of: {1}'.format( signal, ', '.join(msg)) cmd = "{0} {1}".format(__opts__['solr.init_script'], signal) __salt__['cmd.run'](cmd, python_shell=False) def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_core None music Return data is in the following format:: {'success':bool, 'data':dict, 'errors':list, 'warnings':list} ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=RELOAD', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) def core_status(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Get the status for a given core or all cores if no core is specified host : str (None) The solr host to query. __opts__['host'] is default. core_name : str The name of the core to reload Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.core_status None music ''' ret = _get_return_dict() if not _check_for_cores(): err = ['solr.reload_core can only be called by "multi-core" minions'] return ret.update({'success': False, 'errors': err}) if _get_none_or_value(core_name) is None and _check_for_cores(): success = True for name in __opts__['solr.cores']: resp = reload_core(host, name) if not resp['success']: success = False data = {name: {'data': resp['data']}} ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings']) return ret extra = ['action=STATUS', 'core={0}'.format(core_name)] url = _format_url('admin/cores', host=host, core_name=None, extra=extra) return _http_request(url) # ################## DIH (Direct Import Handler) COMMANDS ##################### def reload_import_config(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY re-loads the handler config XML file. This command can only be run if the minion is a 'master' type handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.reload_import_config dataimport None music {'clean':True} ''' # make sure that it's a master minion if not _is_master() and _get_none_or_value(host) is None: err = [ 'solr.pre_indexing_check can only be called by "master" minions'] return _get_return_dict(False, err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=reload-config'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def abort_import(handler, host=None, core_name=None, verbose=False): ''' MASTER ONLY Aborts an existing import command to the specified handler. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. verbose : boolean (False) Run the command with verbose output. Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.abort_import dataimport None music {'clean':True} ''' if not _is_master() and _get_none_or_value(host) is None: err = ['solr.abort_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) params = ['command=abort'] if verbose: params.append("verbose=true") url = _format_url(handler, host=host, core_name=core_name, extra=params) return _http_request(url) def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.full_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master(): err = ['solr.full_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) if _get_none_or_value(core_name) is None and _check_for_cores(): err = ['No core specified when minion is configured as "multi-core".'] return _get_return_dict(False, err) resp = _pre_index_check(handler, host, core_name) if not resp['success']: return resp options = _merge_options(options) if options['clean']: resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=full-import'] for key, val in six.iteritems(options): params.append('&{0}={1}'.format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) def delta_import(handler, host=None, core_name=None, options=None, extra=None): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is default. core : str (None) The core the handler belongs to. options : dict (__opts__) A list of options such as clean, optimize commit, verbose, and pause_replication. leave blank to use __opts__ defaults. options will be merged with __opts__ extra : dict ([]) Extra name value pairs to pass to the handler. e.g. ["name=value"] Return : dict<str,obj>:: {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} CLI Example: .. code-block:: bash salt '*' solr.delta_import dataimport None music {'clean':True} ''' options = {} if options is None else options extra = [] if extra is None else extra if not _is_master() and _get_none_or_value(host) is None: err = ['solr.delta_import can only be called on "master" minions'] return _get_return_dict(False, errors=err) resp = _pre_index_check(handler, host=host, core_name=core_name) if not resp['success']: return resp options = _merge_options(options) # if we're nuking data, and we're multi-core disable replication for safety if options['clean'] and _check_for_cores(): resp = set_replication_enabled(False, host=host, core_name=core_name) if not resp['success']: errors = ['Failed to set the replication status on the master.'] return _get_return_dict(False, errors=errors) params = ['command=delta-import'] for key, val in six.iteritems(options): params.append("{0}={1}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url)
saltstack/salt
salt/utils/decorators/__init__.py
timing
python
def timing(function): ''' Decorator wrapper to log execution time, for profiling purposes ''' @wraps(function) def wrapped(*args, **kwargs): start_time = time.time() ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs)) end_time = time.time() if function.__module__.startswith('salt.loaded.int.'): mod_name = function.__module__[16:] else: mod_name = function.__module__ fstr = 'Function %s.%s took %.{0}f seconds to execute'.format( sys.float_info.dig ) log.profile(fstr, mod_name, function.__name__, end_time - start_time) return ret return wrapped
Decorator wrapper to log execution time, for profiling purposes
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L220-L238
null
# -*- coding: utf-8 -*- ''' Helpful decorators for module writing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import errno import inspect import logging import subprocess import sys import time from functools import wraps from collections import defaultdict # Import salt libs import salt.utils.args import salt.utils.data from salt.exceptions import CommandExecutionError, SaltConfigurationError from salt.log import LOG_LEVELS # Import 3rd-party libs from salt.ext import six IS_WINDOWS = False if getattr(sys, 'getwindowsversion', False): IS_WINDOWS = True log = logging.getLogger(__name__) class Depends(object): ''' This decorator will check the module when it is loaded and check that the dependencies passed in are in the globals of the module. If not, it will cause the function to be unloaded (or replaced). ''' # kind -> Dependency -> list of things that depend on it dependency_dict = defaultdict(lambda: defaultdict(dict)) def __init__(self, *dependencies, **kwargs): ''' The decorator is instantiated with a list of dependencies (string of global name) An example use of this would be: .. code-block:: python @depends('modulename') def test(): return 'foo' OR @depends('modulename', fallback_function=function) def test(): return 'foo' .. code-block:: python This can also be done with the retcode of a command, using the ``retcode`` argument: @depends('/opt/bin/check_cmd', retcode=0) def test(): return 'foo' It is also possible to check for any nonzero retcode using the ``nonzero_retcode`` argument: @depends('/opt/bin/check_cmd', nonzero_retcode=True) def test(): return 'foo' .. note:: The command must be formatted as a string, not a list of args. Additionally, I/O redirection and other shell-specific syntax are not supported since this uses shell=False when calling subprocess.Popen(). ''' log.trace( 'Depends decorator instantiated with dep list of %s and kwargs %s', dependencies, kwargs ) self.dependencies = dependencies self.params = kwargs def __call__(self, function): ''' The decorator is "__call__"d with the function, we take that function and determine which module and function name it is to store in the class wide dependency_dict ''' try: # This inspect call may fail under certain conditions in the loader. # Possibly related to a Python bug here: # http://bugs.python.org/issue17735 frame = inspect.stack()[1][0] # due to missing *.py files under esky we cannot use inspect.getmodule # module name is something like salt.loaded.int.modules.test _, kind, mod_name = frame.f_globals['__name__'].rsplit('.', 2) fun_name = function.__name__ for dep in self.dependencies: self.dependency_dict[kind][dep][(mod_name, fun_name)] = (frame, self.params) except Exception as exc: log.exception( 'Exception encountered when attempting to inspect frame in ' 'dependency decorator' ) return function @staticmethod def run_command(dependency, mod_name, func_name): full_name = '{0}.{1}'.format(mod_name, func_name) log.trace('Running \'%s\' for \'%s\'', dependency, full_name) if IS_WINDOWS: args = salt.utils.args.shlex_split(dependency, posix=False) else: args = salt.utils.args.shlex_split(dependency) log.trace('Command after shlex_split: %s', args) proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = proc.communicate()[0] retcode = proc.returncode log.trace('Output from \'%s\': %s', dependency, output) log.trace('Retcode from \'%s\': %d', dependency, retcode) return retcode @classmethod def enforce_dependencies(cls, functions, kind): ''' This is a class global method to enforce the dependencies that you currently know about. It will modify the "functions" dict and remove/replace modules that are missing dependencies. ''' for dependency, dependent_dict in six.iteritems(cls.dependency_dict[kind]): for (mod_name, func_name), (frame, params) in six.iteritems(dependent_dict): if 'retcode' in params or 'nonzero_retcode' in params: try: retcode = cls.run_command(dependency, mod_name, func_name) except OSError as exc: if exc.errno == errno.ENOENT: log.trace( 'Failed to run command %s, %s not found', dependency, exc.filename ) else: log.trace( 'Failed to run command \'%s\': %s', dependency, exc ) retcode = -1 if 'retcode' in params: if params['retcode'] == retcode: continue elif 'nonzero_retcode' in params: if params['nonzero_retcode']: if retcode != 0: continue else: if retcode == 0: continue # check if dependency is loaded elif dependency is True: log.trace( 'Dependency for %s.%s exists, not unloading', mod_name, func_name ) continue # check if you have the dependency elif dependency in frame.f_globals \ or dependency in frame.f_locals: log.trace( 'Dependency (%s) already loaded inside %s, skipping', dependency, mod_name ) continue log.trace( 'Unloading %s.%s because dependency (%s) is not met', mod_name, func_name, dependency ) # if not, unload the function if frame: try: func_name = frame.f_globals['__func_alias__'][func_name] except (AttributeError, KeyError): pass mod_key = '{0}.{1}'.format(mod_name, func_name) # if we don't have this module loaded, skip it! if mod_key not in functions: continue try: fallback_function = params.get('fallback_function') if fallback_function is not None: functions[mod_key] = fallback_function else: del functions[mod_key] except AttributeError: # we already did??? log.trace('%s already removed, skipping', mod_key) continue depends = Depends def memoize(func): ''' Memoize aka cache the return output of a function given a specific set of arguments .. versionedited:: 2016.3.4 Added **kwargs support. ''' cache = {} @wraps(func) def _memoize(*args, **kwargs): str_args = [] for arg in args: if not isinstance(arg, six.string_types): str_args.append(six.text_type(arg)) else: str_args.append(arg) args_ = ','.join(list(str_args) + ['{0}={1}'.format(k, kwargs[k]) for k in sorted(kwargs)]) if args_ not in cache: cache[args_] = func(*args, **kwargs) return cache[args_] return _memoize class _DeprecationDecorator(object): ''' Base mix-in class for the deprecation decorator. Takes care of a common functionality, used in its derivatives. ''' OPT_IN = 1 OPT_OUT = 2 def __init__(self, globals, version): ''' Constructor. :param globals: Module globals. Important for finding out replacement functions :param version: Expiration version :return: ''' from salt.version import SaltStackVersion, __saltstack_version__ self._globals = globals self._exp_version_name = version self._exp_version = SaltStackVersion.from_name(self._exp_version_name) self._curr_version = __saltstack_version__.info self._raise_later = None self._function = None self._orig_f_name = None def _get_args(self, kwargs): ''' Discard all keywords which aren't function-specific from the kwargs. :param kwargs: :return: ''' _args = list() _kwargs = salt.utils.args.clean_kwargs(**kwargs) return _args, _kwargs def _call_function(self, kwargs): ''' Call target function that has been decorated. :return: ''' if self._raise_later: raise self._raise_later # pylint: disable=E0702 if self._function: args, kwargs = self._get_args(kwargs) try: return self._function(*args, **kwargs) except TypeError as error: error = six.text_type(error).replace(self._function, self._orig_f_name) # Hide hidden functions log.error( 'Function "%s" was not properly called: %s', self._orig_f_name, error ) return self._function.__doc__ except Exception as error: log.error( 'Unhandled exception occurred in function "%s: %s', self._function.__name__, error ) raise error else: raise CommandExecutionError("Function is deprecated, but the successor function was not found.") def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' self._function = function self._orig_f_name = self._function.__name__ class _IsDeprecated(_DeprecationDecorator): ''' This decorator should be used only with the deprecated functions to mark them as deprecated and alter its behavior a corresponding way. The usage is only suitable if deprecation process is renaming the function from one to another. In case function name or even function signature stays the same, please use 'with_deprecated' decorator instead. It has the following functionality: 1. Put a warning level message to the log, informing that the deprecated function has been in use. 2. Raise an exception, if deprecated function is being called, but the lifetime of it already expired. 3. Point to the successor of the deprecated function in the log messages as well during the blocking it, once expired. Usage of this decorator as follows. In this example no successor is mentioned, hence the function "foo()" will be logged with the warning each time is called and blocked completely, once EOF of it is reached: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium") def foo(): pass In the following example a successor function is mentioned, hence every time the function "bar()" is called, message will suggest to use function "baz()" instead. Once EOF is reached of the function "bar()", an exception will ask to use function "baz()", in order to continue: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium", with_successor="baz") def bar(): pass def baz(): pass ''' def __init__(self, globals, version, with_successor=None): ''' Constructor of the decorator 'is_deprecated'. :param globals: Module globals :param version: Version to be deprecated :param with_successor: Successor function (optional) :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._successor = with_successor def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' if self._curr_version < self._exp_version: msg = ['The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format(f_name=self._function.__name__, version_name=self._exp_version_name)] if self._successor: msg.append('Use successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) else: msg = ['The lifetime of the function "{f_name}" expired.'.format(f_name=self._function.__name__)] if self._successor: msg.append('Please use its successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) return _decorate is_deprecated = _IsDeprecated class _WithDeprecated(_DeprecationDecorator): ''' This decorator should be used with the successor functions to mark them as a new and alter its behavior in a corresponding way. It is used alone if a function content or function signature needs to be replaced, leaving the name of the function same. In case function needs to be renamed or just dropped, it has to be used in pair with 'is_deprecated' decorator. It has the following functionality: 1. Put a warning level message to the log, in case a component is using its deprecated version. 2. Switch between old and new function in case an older version is configured for the desired use. 3. Raise an exception, if deprecated version reached EOL and point out for the new version. Usage of this decorator as follows. If 'with_name' is not specified, then the name of the deprecated function is assumed with the "_" prefix. In this case, in order to deprecate a function, it is required: - Add a prefix "_" to an existing function. E.g.: "foo()" to "_foo()". - Implement a new function with exactly the same name, just without the prefix "_". Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium") def foo(): "This is a new function" def _foo(): "This is a deprecated function" In case there is a need to deprecate a function and rename it, the decorator should be used with the 'with_name' parameter. This parameter is pointing to the existing deprecated function. In this case deprecation process as follows: - Leave a deprecated function without changes, as is. - Implement a new function and decorate it with this decorator. - Set a parameter 'with_name' to the deprecated function. - If a new function has a different name than a deprecated, decorate a deprecated function with the 'is_deprecated' decorator in order to let the function have a deprecated behavior. Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium", with_name="an_old_function") def a_new_function(): "This is a new function" @is_deprecated(globals(), "Beryllium", with_successor="a_new_function") def an_old_function(): "This is a deprecated function" ''' MODULE_NAME = '__virtualname__' CFG_USE_DEPRECATED = 'use_deprecated' CFG_USE_SUPERSEDED = 'use_superseded' def __init__(self, globals, version, with_name=None, policy=_DeprecationDecorator.OPT_OUT): ''' Constructor of the decorator 'with_deprecated' :param globals: :param version: :param with_name: :param policy: :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._with_name = with_name self._policy = policy def _set_function(self, function): ''' Based on the configuration, set to execute an old or a new function. :return: ''' full_name = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=function.__name__) if full_name.startswith("."): self._raise_later = CommandExecutionError('Module not found for function "{f_name}"'.format( f_name=function.__name__)) opts = self._globals.get('__opts__', '{}') pillar = self._globals.get('__pillar__', '{}') use_deprecated = (full_name in opts.get(self.CFG_USE_DEPRECATED, list()) or full_name in pillar.get(self.CFG_USE_DEPRECATED, list())) use_superseded = (full_name in opts.get(self.CFG_USE_SUPERSEDED, list()) or full_name in pillar.get(self.CFG_USE_SUPERSEDED, list())) if use_deprecated and use_superseded: raise SaltConfigurationError("Function '{0}' is mentioned both in deprecated " "and superseded sections. Please remove any of that.".format(full_name)) old_function = self._globals.get(self._with_name or "_{0}".format(function.__name__)) if self._policy == self.OPT_IN: self._function = function if use_superseded else old_function else: self._function = old_function if use_deprecated else function def _is_used_deprecated(self): ''' Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return: ''' func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=self._orig_f_name) return func_path in self._globals.get('__opts__').get( self.CFG_USE_DEPRECATED, list()) or func_path in self._globals.get('__pillar__').get( self.CFG_USE_DEPRECATED, list()) or (self._policy == self.OPT_IN and not (func_path in self._globals.get('__opts__', {}).get( self.CFG_USE_SUPERSEDED, list())) and not (func_path in self._globals.get('__pillar__', {}).get( self.CFG_USE_SUPERSEDED, list()))), func_path def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' self._set_function(function) is_deprecated, func_path = self._is_used_deprecated() if is_deprecated: if self._curr_version < self._exp_version: msg = list() if self._with_name: msg.append('The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format( f_name=self._with_name.startswith("_") and self._orig_f_name or self._with_name, version_name=self._exp_version_name)) msg.append('Use its successor "{successor}" instead.'.format(successor=self._orig_f_name)) else: msg.append('The function "{f_name}" is using its deprecated version and will ' 'expire in version "{version_name}".'.format(f_name=func_path, version_name=self._exp_version_name)) log.warning(' '.join(msg)) else: msg_patt = 'The lifetime of the function "{f_name}" expired.' if '_' + self._orig_f_name == self._function.__name__: msg = [msg_patt.format(f_name=self._orig_f_name), 'Please turn off its deprecated version in the configuration'] else: msg = ['Although function "{f_name}" is called, an alias "{f_alias}" ' 'is configured as its deprecated version.'.format( f_name=self._orig_f_name, f_alias=self._with_name or self._orig_f_name), msg_patt.format(f_name=self._with_name or self._orig_f_name), 'Please use its successor "{successor}" instead.'.format(successor=self._orig_f_name)] log.error(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) _decorate.__doc__ = self._function.__doc__ return _decorate with_deprecated = _WithDeprecated def ignores_kwargs(*kwarg_names): ''' Decorator to filter out unexpected keyword arguments from the call kwarg_names: List of argument names to ignore ''' def _ignores_kwargs(fn): def __ignores_kwargs(*args, **kwargs): kwargs_filtered = kwargs.copy() for name in kwarg_names: if name in kwargs_filtered: del kwargs_filtered[name] return fn(*args, **kwargs_filtered) return __ignores_kwargs return _ignores_kwargs def ensure_unicode_args(function): ''' Decodes all arguments passed to the wrapped function ''' @wraps(function) def wrapped(*args, **kwargs): if six.PY2: return function( *salt.utils.data.decode_list(args), **salt.utils.data.decode_dict(kwargs) ) else: return function(*args, **kwargs) return wrapped def external(func): ''' Mark function as external. :param func: :return: ''' def f(*args, **kwargs): ''' Stub. :param args: :param kwargs: :return: ''' return func(*args, **kwargs) f.external = True f.__doc__ = func.__doc__ return f
saltstack/salt
salt/utils/decorators/__init__.py
memoize
python
def memoize(func): ''' Memoize aka cache the return output of a function given a specific set of arguments .. versionedited:: 2016.3.4 Added **kwargs support. ''' cache = {} @wraps(func) def _memoize(*args, **kwargs): str_args = [] for arg in args: if not isinstance(arg, six.string_types): str_args.append(six.text_type(arg)) else: str_args.append(arg) args_ = ','.join(list(str_args) + ['{0}={1}'.format(k, kwargs[k]) for k in sorted(kwargs)]) if args_ not in cache: cache[args_] = func(*args, **kwargs) return cache[args_] return _memoize
Memoize aka cache the return output of a function given a specific set of arguments .. versionedited:: 2016.3.4 Added **kwargs support.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L241-L266
null
# -*- coding: utf-8 -*- ''' Helpful decorators for module writing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import errno import inspect import logging import subprocess import sys import time from functools import wraps from collections import defaultdict # Import salt libs import salt.utils.args import salt.utils.data from salt.exceptions import CommandExecutionError, SaltConfigurationError from salt.log import LOG_LEVELS # Import 3rd-party libs from salt.ext import six IS_WINDOWS = False if getattr(sys, 'getwindowsversion', False): IS_WINDOWS = True log = logging.getLogger(__name__) class Depends(object): ''' This decorator will check the module when it is loaded and check that the dependencies passed in are in the globals of the module. If not, it will cause the function to be unloaded (or replaced). ''' # kind -> Dependency -> list of things that depend on it dependency_dict = defaultdict(lambda: defaultdict(dict)) def __init__(self, *dependencies, **kwargs): ''' The decorator is instantiated with a list of dependencies (string of global name) An example use of this would be: .. code-block:: python @depends('modulename') def test(): return 'foo' OR @depends('modulename', fallback_function=function) def test(): return 'foo' .. code-block:: python This can also be done with the retcode of a command, using the ``retcode`` argument: @depends('/opt/bin/check_cmd', retcode=0) def test(): return 'foo' It is also possible to check for any nonzero retcode using the ``nonzero_retcode`` argument: @depends('/opt/bin/check_cmd', nonzero_retcode=True) def test(): return 'foo' .. note:: The command must be formatted as a string, not a list of args. Additionally, I/O redirection and other shell-specific syntax are not supported since this uses shell=False when calling subprocess.Popen(). ''' log.trace( 'Depends decorator instantiated with dep list of %s and kwargs %s', dependencies, kwargs ) self.dependencies = dependencies self.params = kwargs def __call__(self, function): ''' The decorator is "__call__"d with the function, we take that function and determine which module and function name it is to store in the class wide dependency_dict ''' try: # This inspect call may fail under certain conditions in the loader. # Possibly related to a Python bug here: # http://bugs.python.org/issue17735 frame = inspect.stack()[1][0] # due to missing *.py files under esky we cannot use inspect.getmodule # module name is something like salt.loaded.int.modules.test _, kind, mod_name = frame.f_globals['__name__'].rsplit('.', 2) fun_name = function.__name__ for dep in self.dependencies: self.dependency_dict[kind][dep][(mod_name, fun_name)] = (frame, self.params) except Exception as exc: log.exception( 'Exception encountered when attempting to inspect frame in ' 'dependency decorator' ) return function @staticmethod def run_command(dependency, mod_name, func_name): full_name = '{0}.{1}'.format(mod_name, func_name) log.trace('Running \'%s\' for \'%s\'', dependency, full_name) if IS_WINDOWS: args = salt.utils.args.shlex_split(dependency, posix=False) else: args = salt.utils.args.shlex_split(dependency) log.trace('Command after shlex_split: %s', args) proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = proc.communicate()[0] retcode = proc.returncode log.trace('Output from \'%s\': %s', dependency, output) log.trace('Retcode from \'%s\': %d', dependency, retcode) return retcode @classmethod def enforce_dependencies(cls, functions, kind): ''' This is a class global method to enforce the dependencies that you currently know about. It will modify the "functions" dict and remove/replace modules that are missing dependencies. ''' for dependency, dependent_dict in six.iteritems(cls.dependency_dict[kind]): for (mod_name, func_name), (frame, params) in six.iteritems(dependent_dict): if 'retcode' in params or 'nonzero_retcode' in params: try: retcode = cls.run_command(dependency, mod_name, func_name) except OSError as exc: if exc.errno == errno.ENOENT: log.trace( 'Failed to run command %s, %s not found', dependency, exc.filename ) else: log.trace( 'Failed to run command \'%s\': %s', dependency, exc ) retcode = -1 if 'retcode' in params: if params['retcode'] == retcode: continue elif 'nonzero_retcode' in params: if params['nonzero_retcode']: if retcode != 0: continue else: if retcode == 0: continue # check if dependency is loaded elif dependency is True: log.trace( 'Dependency for %s.%s exists, not unloading', mod_name, func_name ) continue # check if you have the dependency elif dependency in frame.f_globals \ or dependency in frame.f_locals: log.trace( 'Dependency (%s) already loaded inside %s, skipping', dependency, mod_name ) continue log.trace( 'Unloading %s.%s because dependency (%s) is not met', mod_name, func_name, dependency ) # if not, unload the function if frame: try: func_name = frame.f_globals['__func_alias__'][func_name] except (AttributeError, KeyError): pass mod_key = '{0}.{1}'.format(mod_name, func_name) # if we don't have this module loaded, skip it! if mod_key not in functions: continue try: fallback_function = params.get('fallback_function') if fallback_function is not None: functions[mod_key] = fallback_function else: del functions[mod_key] except AttributeError: # we already did??? log.trace('%s already removed, skipping', mod_key) continue depends = Depends def timing(function): ''' Decorator wrapper to log execution time, for profiling purposes ''' @wraps(function) def wrapped(*args, **kwargs): start_time = time.time() ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs)) end_time = time.time() if function.__module__.startswith('salt.loaded.int.'): mod_name = function.__module__[16:] else: mod_name = function.__module__ fstr = 'Function %s.%s took %.{0}f seconds to execute'.format( sys.float_info.dig ) log.profile(fstr, mod_name, function.__name__, end_time - start_time) return ret return wrapped class _DeprecationDecorator(object): ''' Base mix-in class for the deprecation decorator. Takes care of a common functionality, used in its derivatives. ''' OPT_IN = 1 OPT_OUT = 2 def __init__(self, globals, version): ''' Constructor. :param globals: Module globals. Important for finding out replacement functions :param version: Expiration version :return: ''' from salt.version import SaltStackVersion, __saltstack_version__ self._globals = globals self._exp_version_name = version self._exp_version = SaltStackVersion.from_name(self._exp_version_name) self._curr_version = __saltstack_version__.info self._raise_later = None self._function = None self._orig_f_name = None def _get_args(self, kwargs): ''' Discard all keywords which aren't function-specific from the kwargs. :param kwargs: :return: ''' _args = list() _kwargs = salt.utils.args.clean_kwargs(**kwargs) return _args, _kwargs def _call_function(self, kwargs): ''' Call target function that has been decorated. :return: ''' if self._raise_later: raise self._raise_later # pylint: disable=E0702 if self._function: args, kwargs = self._get_args(kwargs) try: return self._function(*args, **kwargs) except TypeError as error: error = six.text_type(error).replace(self._function, self._orig_f_name) # Hide hidden functions log.error( 'Function "%s" was not properly called: %s', self._orig_f_name, error ) return self._function.__doc__ except Exception as error: log.error( 'Unhandled exception occurred in function "%s: %s', self._function.__name__, error ) raise error else: raise CommandExecutionError("Function is deprecated, but the successor function was not found.") def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' self._function = function self._orig_f_name = self._function.__name__ class _IsDeprecated(_DeprecationDecorator): ''' This decorator should be used only with the deprecated functions to mark them as deprecated and alter its behavior a corresponding way. The usage is only suitable if deprecation process is renaming the function from one to another. In case function name or even function signature stays the same, please use 'with_deprecated' decorator instead. It has the following functionality: 1. Put a warning level message to the log, informing that the deprecated function has been in use. 2. Raise an exception, if deprecated function is being called, but the lifetime of it already expired. 3. Point to the successor of the deprecated function in the log messages as well during the blocking it, once expired. Usage of this decorator as follows. In this example no successor is mentioned, hence the function "foo()" will be logged with the warning each time is called and blocked completely, once EOF of it is reached: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium") def foo(): pass In the following example a successor function is mentioned, hence every time the function "bar()" is called, message will suggest to use function "baz()" instead. Once EOF is reached of the function "bar()", an exception will ask to use function "baz()", in order to continue: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium", with_successor="baz") def bar(): pass def baz(): pass ''' def __init__(self, globals, version, with_successor=None): ''' Constructor of the decorator 'is_deprecated'. :param globals: Module globals :param version: Version to be deprecated :param with_successor: Successor function (optional) :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._successor = with_successor def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' if self._curr_version < self._exp_version: msg = ['The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format(f_name=self._function.__name__, version_name=self._exp_version_name)] if self._successor: msg.append('Use successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) else: msg = ['The lifetime of the function "{f_name}" expired.'.format(f_name=self._function.__name__)] if self._successor: msg.append('Please use its successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) return _decorate is_deprecated = _IsDeprecated class _WithDeprecated(_DeprecationDecorator): ''' This decorator should be used with the successor functions to mark them as a new and alter its behavior in a corresponding way. It is used alone if a function content or function signature needs to be replaced, leaving the name of the function same. In case function needs to be renamed or just dropped, it has to be used in pair with 'is_deprecated' decorator. It has the following functionality: 1. Put a warning level message to the log, in case a component is using its deprecated version. 2. Switch between old and new function in case an older version is configured for the desired use. 3. Raise an exception, if deprecated version reached EOL and point out for the new version. Usage of this decorator as follows. If 'with_name' is not specified, then the name of the deprecated function is assumed with the "_" prefix. In this case, in order to deprecate a function, it is required: - Add a prefix "_" to an existing function. E.g.: "foo()" to "_foo()". - Implement a new function with exactly the same name, just without the prefix "_". Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium") def foo(): "This is a new function" def _foo(): "This is a deprecated function" In case there is a need to deprecate a function and rename it, the decorator should be used with the 'with_name' parameter. This parameter is pointing to the existing deprecated function. In this case deprecation process as follows: - Leave a deprecated function without changes, as is. - Implement a new function and decorate it with this decorator. - Set a parameter 'with_name' to the deprecated function. - If a new function has a different name than a deprecated, decorate a deprecated function with the 'is_deprecated' decorator in order to let the function have a deprecated behavior. Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium", with_name="an_old_function") def a_new_function(): "This is a new function" @is_deprecated(globals(), "Beryllium", with_successor="a_new_function") def an_old_function(): "This is a deprecated function" ''' MODULE_NAME = '__virtualname__' CFG_USE_DEPRECATED = 'use_deprecated' CFG_USE_SUPERSEDED = 'use_superseded' def __init__(self, globals, version, with_name=None, policy=_DeprecationDecorator.OPT_OUT): ''' Constructor of the decorator 'with_deprecated' :param globals: :param version: :param with_name: :param policy: :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._with_name = with_name self._policy = policy def _set_function(self, function): ''' Based on the configuration, set to execute an old or a new function. :return: ''' full_name = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=function.__name__) if full_name.startswith("."): self._raise_later = CommandExecutionError('Module not found for function "{f_name}"'.format( f_name=function.__name__)) opts = self._globals.get('__opts__', '{}') pillar = self._globals.get('__pillar__', '{}') use_deprecated = (full_name in opts.get(self.CFG_USE_DEPRECATED, list()) or full_name in pillar.get(self.CFG_USE_DEPRECATED, list())) use_superseded = (full_name in opts.get(self.CFG_USE_SUPERSEDED, list()) or full_name in pillar.get(self.CFG_USE_SUPERSEDED, list())) if use_deprecated and use_superseded: raise SaltConfigurationError("Function '{0}' is mentioned both in deprecated " "and superseded sections. Please remove any of that.".format(full_name)) old_function = self._globals.get(self._with_name or "_{0}".format(function.__name__)) if self._policy == self.OPT_IN: self._function = function if use_superseded else old_function else: self._function = old_function if use_deprecated else function def _is_used_deprecated(self): ''' Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return: ''' func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=self._orig_f_name) return func_path in self._globals.get('__opts__').get( self.CFG_USE_DEPRECATED, list()) or func_path in self._globals.get('__pillar__').get( self.CFG_USE_DEPRECATED, list()) or (self._policy == self.OPT_IN and not (func_path in self._globals.get('__opts__', {}).get( self.CFG_USE_SUPERSEDED, list())) and not (func_path in self._globals.get('__pillar__', {}).get( self.CFG_USE_SUPERSEDED, list()))), func_path def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' self._set_function(function) is_deprecated, func_path = self._is_used_deprecated() if is_deprecated: if self._curr_version < self._exp_version: msg = list() if self._with_name: msg.append('The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format( f_name=self._with_name.startswith("_") and self._orig_f_name or self._with_name, version_name=self._exp_version_name)) msg.append('Use its successor "{successor}" instead.'.format(successor=self._orig_f_name)) else: msg.append('The function "{f_name}" is using its deprecated version and will ' 'expire in version "{version_name}".'.format(f_name=func_path, version_name=self._exp_version_name)) log.warning(' '.join(msg)) else: msg_patt = 'The lifetime of the function "{f_name}" expired.' if '_' + self._orig_f_name == self._function.__name__: msg = [msg_patt.format(f_name=self._orig_f_name), 'Please turn off its deprecated version in the configuration'] else: msg = ['Although function "{f_name}" is called, an alias "{f_alias}" ' 'is configured as its deprecated version.'.format( f_name=self._orig_f_name, f_alias=self._with_name or self._orig_f_name), msg_patt.format(f_name=self._with_name or self._orig_f_name), 'Please use its successor "{successor}" instead.'.format(successor=self._orig_f_name)] log.error(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) _decorate.__doc__ = self._function.__doc__ return _decorate with_deprecated = _WithDeprecated def ignores_kwargs(*kwarg_names): ''' Decorator to filter out unexpected keyword arguments from the call kwarg_names: List of argument names to ignore ''' def _ignores_kwargs(fn): def __ignores_kwargs(*args, **kwargs): kwargs_filtered = kwargs.copy() for name in kwarg_names: if name in kwargs_filtered: del kwargs_filtered[name] return fn(*args, **kwargs_filtered) return __ignores_kwargs return _ignores_kwargs def ensure_unicode_args(function): ''' Decodes all arguments passed to the wrapped function ''' @wraps(function) def wrapped(*args, **kwargs): if six.PY2: return function( *salt.utils.data.decode_list(args), **salt.utils.data.decode_dict(kwargs) ) else: return function(*args, **kwargs) return wrapped def external(func): ''' Mark function as external. :param func: :return: ''' def f(*args, **kwargs): ''' Stub. :param args: :param kwargs: :return: ''' return func(*args, **kwargs) f.external = True f.__doc__ = func.__doc__ return f
saltstack/salt
salt/utils/decorators/__init__.py
ignores_kwargs
python
def ignores_kwargs(*kwarg_names): ''' Decorator to filter out unexpected keyword arguments from the call kwarg_names: List of argument names to ignore ''' def _ignores_kwargs(fn): def __ignores_kwargs(*args, **kwargs): kwargs_filtered = kwargs.copy() for name in kwarg_names: if name in kwargs_filtered: del kwargs_filtered[name] return fn(*args, **kwargs_filtered) return __ignores_kwargs return _ignores_kwargs
Decorator to filter out unexpected keyword arguments from the call kwarg_names: List of argument names to ignore
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L636-L651
null
# -*- coding: utf-8 -*- ''' Helpful decorators for module writing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import errno import inspect import logging import subprocess import sys import time from functools import wraps from collections import defaultdict # Import salt libs import salt.utils.args import salt.utils.data from salt.exceptions import CommandExecutionError, SaltConfigurationError from salt.log import LOG_LEVELS # Import 3rd-party libs from salt.ext import six IS_WINDOWS = False if getattr(sys, 'getwindowsversion', False): IS_WINDOWS = True log = logging.getLogger(__name__) class Depends(object): ''' This decorator will check the module when it is loaded and check that the dependencies passed in are in the globals of the module. If not, it will cause the function to be unloaded (or replaced). ''' # kind -> Dependency -> list of things that depend on it dependency_dict = defaultdict(lambda: defaultdict(dict)) def __init__(self, *dependencies, **kwargs): ''' The decorator is instantiated with a list of dependencies (string of global name) An example use of this would be: .. code-block:: python @depends('modulename') def test(): return 'foo' OR @depends('modulename', fallback_function=function) def test(): return 'foo' .. code-block:: python This can also be done with the retcode of a command, using the ``retcode`` argument: @depends('/opt/bin/check_cmd', retcode=0) def test(): return 'foo' It is also possible to check for any nonzero retcode using the ``nonzero_retcode`` argument: @depends('/opt/bin/check_cmd', nonzero_retcode=True) def test(): return 'foo' .. note:: The command must be formatted as a string, not a list of args. Additionally, I/O redirection and other shell-specific syntax are not supported since this uses shell=False when calling subprocess.Popen(). ''' log.trace( 'Depends decorator instantiated with dep list of %s and kwargs %s', dependencies, kwargs ) self.dependencies = dependencies self.params = kwargs def __call__(self, function): ''' The decorator is "__call__"d with the function, we take that function and determine which module and function name it is to store in the class wide dependency_dict ''' try: # This inspect call may fail under certain conditions in the loader. # Possibly related to a Python bug here: # http://bugs.python.org/issue17735 frame = inspect.stack()[1][0] # due to missing *.py files under esky we cannot use inspect.getmodule # module name is something like salt.loaded.int.modules.test _, kind, mod_name = frame.f_globals['__name__'].rsplit('.', 2) fun_name = function.__name__ for dep in self.dependencies: self.dependency_dict[kind][dep][(mod_name, fun_name)] = (frame, self.params) except Exception as exc: log.exception( 'Exception encountered when attempting to inspect frame in ' 'dependency decorator' ) return function @staticmethod def run_command(dependency, mod_name, func_name): full_name = '{0}.{1}'.format(mod_name, func_name) log.trace('Running \'%s\' for \'%s\'', dependency, full_name) if IS_WINDOWS: args = salt.utils.args.shlex_split(dependency, posix=False) else: args = salt.utils.args.shlex_split(dependency) log.trace('Command after shlex_split: %s', args) proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = proc.communicate()[0] retcode = proc.returncode log.trace('Output from \'%s\': %s', dependency, output) log.trace('Retcode from \'%s\': %d', dependency, retcode) return retcode @classmethod def enforce_dependencies(cls, functions, kind): ''' This is a class global method to enforce the dependencies that you currently know about. It will modify the "functions" dict and remove/replace modules that are missing dependencies. ''' for dependency, dependent_dict in six.iteritems(cls.dependency_dict[kind]): for (mod_name, func_name), (frame, params) in six.iteritems(dependent_dict): if 'retcode' in params or 'nonzero_retcode' in params: try: retcode = cls.run_command(dependency, mod_name, func_name) except OSError as exc: if exc.errno == errno.ENOENT: log.trace( 'Failed to run command %s, %s not found', dependency, exc.filename ) else: log.trace( 'Failed to run command \'%s\': %s', dependency, exc ) retcode = -1 if 'retcode' in params: if params['retcode'] == retcode: continue elif 'nonzero_retcode' in params: if params['nonzero_retcode']: if retcode != 0: continue else: if retcode == 0: continue # check if dependency is loaded elif dependency is True: log.trace( 'Dependency for %s.%s exists, not unloading', mod_name, func_name ) continue # check if you have the dependency elif dependency in frame.f_globals \ or dependency in frame.f_locals: log.trace( 'Dependency (%s) already loaded inside %s, skipping', dependency, mod_name ) continue log.trace( 'Unloading %s.%s because dependency (%s) is not met', mod_name, func_name, dependency ) # if not, unload the function if frame: try: func_name = frame.f_globals['__func_alias__'][func_name] except (AttributeError, KeyError): pass mod_key = '{0}.{1}'.format(mod_name, func_name) # if we don't have this module loaded, skip it! if mod_key not in functions: continue try: fallback_function = params.get('fallback_function') if fallback_function is not None: functions[mod_key] = fallback_function else: del functions[mod_key] except AttributeError: # we already did??? log.trace('%s already removed, skipping', mod_key) continue depends = Depends def timing(function): ''' Decorator wrapper to log execution time, for profiling purposes ''' @wraps(function) def wrapped(*args, **kwargs): start_time = time.time() ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs)) end_time = time.time() if function.__module__.startswith('salt.loaded.int.'): mod_name = function.__module__[16:] else: mod_name = function.__module__ fstr = 'Function %s.%s took %.{0}f seconds to execute'.format( sys.float_info.dig ) log.profile(fstr, mod_name, function.__name__, end_time - start_time) return ret return wrapped def memoize(func): ''' Memoize aka cache the return output of a function given a specific set of arguments .. versionedited:: 2016.3.4 Added **kwargs support. ''' cache = {} @wraps(func) def _memoize(*args, **kwargs): str_args = [] for arg in args: if not isinstance(arg, six.string_types): str_args.append(six.text_type(arg)) else: str_args.append(arg) args_ = ','.join(list(str_args) + ['{0}={1}'.format(k, kwargs[k]) for k in sorted(kwargs)]) if args_ not in cache: cache[args_] = func(*args, **kwargs) return cache[args_] return _memoize class _DeprecationDecorator(object): ''' Base mix-in class for the deprecation decorator. Takes care of a common functionality, used in its derivatives. ''' OPT_IN = 1 OPT_OUT = 2 def __init__(self, globals, version): ''' Constructor. :param globals: Module globals. Important for finding out replacement functions :param version: Expiration version :return: ''' from salt.version import SaltStackVersion, __saltstack_version__ self._globals = globals self._exp_version_name = version self._exp_version = SaltStackVersion.from_name(self._exp_version_name) self._curr_version = __saltstack_version__.info self._raise_later = None self._function = None self._orig_f_name = None def _get_args(self, kwargs): ''' Discard all keywords which aren't function-specific from the kwargs. :param kwargs: :return: ''' _args = list() _kwargs = salt.utils.args.clean_kwargs(**kwargs) return _args, _kwargs def _call_function(self, kwargs): ''' Call target function that has been decorated. :return: ''' if self._raise_later: raise self._raise_later # pylint: disable=E0702 if self._function: args, kwargs = self._get_args(kwargs) try: return self._function(*args, **kwargs) except TypeError as error: error = six.text_type(error).replace(self._function, self._orig_f_name) # Hide hidden functions log.error( 'Function "%s" was not properly called: %s', self._orig_f_name, error ) return self._function.__doc__ except Exception as error: log.error( 'Unhandled exception occurred in function "%s: %s', self._function.__name__, error ) raise error else: raise CommandExecutionError("Function is deprecated, but the successor function was not found.") def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' self._function = function self._orig_f_name = self._function.__name__ class _IsDeprecated(_DeprecationDecorator): ''' This decorator should be used only with the deprecated functions to mark them as deprecated and alter its behavior a corresponding way. The usage is only suitable if deprecation process is renaming the function from one to another. In case function name or even function signature stays the same, please use 'with_deprecated' decorator instead. It has the following functionality: 1. Put a warning level message to the log, informing that the deprecated function has been in use. 2. Raise an exception, if deprecated function is being called, but the lifetime of it already expired. 3. Point to the successor of the deprecated function in the log messages as well during the blocking it, once expired. Usage of this decorator as follows. In this example no successor is mentioned, hence the function "foo()" will be logged with the warning each time is called and blocked completely, once EOF of it is reached: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium") def foo(): pass In the following example a successor function is mentioned, hence every time the function "bar()" is called, message will suggest to use function "baz()" instead. Once EOF is reached of the function "bar()", an exception will ask to use function "baz()", in order to continue: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium", with_successor="baz") def bar(): pass def baz(): pass ''' def __init__(self, globals, version, with_successor=None): ''' Constructor of the decorator 'is_deprecated'. :param globals: Module globals :param version: Version to be deprecated :param with_successor: Successor function (optional) :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._successor = with_successor def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' if self._curr_version < self._exp_version: msg = ['The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format(f_name=self._function.__name__, version_name=self._exp_version_name)] if self._successor: msg.append('Use successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) else: msg = ['The lifetime of the function "{f_name}" expired.'.format(f_name=self._function.__name__)] if self._successor: msg.append('Please use its successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) return _decorate is_deprecated = _IsDeprecated class _WithDeprecated(_DeprecationDecorator): ''' This decorator should be used with the successor functions to mark them as a new and alter its behavior in a corresponding way. It is used alone if a function content or function signature needs to be replaced, leaving the name of the function same. In case function needs to be renamed or just dropped, it has to be used in pair with 'is_deprecated' decorator. It has the following functionality: 1. Put a warning level message to the log, in case a component is using its deprecated version. 2. Switch between old and new function in case an older version is configured for the desired use. 3. Raise an exception, if deprecated version reached EOL and point out for the new version. Usage of this decorator as follows. If 'with_name' is not specified, then the name of the deprecated function is assumed with the "_" prefix. In this case, in order to deprecate a function, it is required: - Add a prefix "_" to an existing function. E.g.: "foo()" to "_foo()". - Implement a new function with exactly the same name, just without the prefix "_". Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium") def foo(): "This is a new function" def _foo(): "This is a deprecated function" In case there is a need to deprecate a function and rename it, the decorator should be used with the 'with_name' parameter. This parameter is pointing to the existing deprecated function. In this case deprecation process as follows: - Leave a deprecated function without changes, as is. - Implement a new function and decorate it with this decorator. - Set a parameter 'with_name' to the deprecated function. - If a new function has a different name than a deprecated, decorate a deprecated function with the 'is_deprecated' decorator in order to let the function have a deprecated behavior. Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium", with_name="an_old_function") def a_new_function(): "This is a new function" @is_deprecated(globals(), "Beryllium", with_successor="a_new_function") def an_old_function(): "This is a deprecated function" ''' MODULE_NAME = '__virtualname__' CFG_USE_DEPRECATED = 'use_deprecated' CFG_USE_SUPERSEDED = 'use_superseded' def __init__(self, globals, version, with_name=None, policy=_DeprecationDecorator.OPT_OUT): ''' Constructor of the decorator 'with_deprecated' :param globals: :param version: :param with_name: :param policy: :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._with_name = with_name self._policy = policy def _set_function(self, function): ''' Based on the configuration, set to execute an old or a new function. :return: ''' full_name = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=function.__name__) if full_name.startswith("."): self._raise_later = CommandExecutionError('Module not found for function "{f_name}"'.format( f_name=function.__name__)) opts = self._globals.get('__opts__', '{}') pillar = self._globals.get('__pillar__', '{}') use_deprecated = (full_name in opts.get(self.CFG_USE_DEPRECATED, list()) or full_name in pillar.get(self.CFG_USE_DEPRECATED, list())) use_superseded = (full_name in opts.get(self.CFG_USE_SUPERSEDED, list()) or full_name in pillar.get(self.CFG_USE_SUPERSEDED, list())) if use_deprecated and use_superseded: raise SaltConfigurationError("Function '{0}' is mentioned both in deprecated " "and superseded sections. Please remove any of that.".format(full_name)) old_function = self._globals.get(self._with_name or "_{0}".format(function.__name__)) if self._policy == self.OPT_IN: self._function = function if use_superseded else old_function else: self._function = old_function if use_deprecated else function def _is_used_deprecated(self): ''' Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return: ''' func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=self._orig_f_name) return func_path in self._globals.get('__opts__').get( self.CFG_USE_DEPRECATED, list()) or func_path in self._globals.get('__pillar__').get( self.CFG_USE_DEPRECATED, list()) or (self._policy == self.OPT_IN and not (func_path in self._globals.get('__opts__', {}).get( self.CFG_USE_SUPERSEDED, list())) and not (func_path in self._globals.get('__pillar__', {}).get( self.CFG_USE_SUPERSEDED, list()))), func_path def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' self._set_function(function) is_deprecated, func_path = self._is_used_deprecated() if is_deprecated: if self._curr_version < self._exp_version: msg = list() if self._with_name: msg.append('The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format( f_name=self._with_name.startswith("_") and self._orig_f_name or self._with_name, version_name=self._exp_version_name)) msg.append('Use its successor "{successor}" instead.'.format(successor=self._orig_f_name)) else: msg.append('The function "{f_name}" is using its deprecated version and will ' 'expire in version "{version_name}".'.format(f_name=func_path, version_name=self._exp_version_name)) log.warning(' '.join(msg)) else: msg_patt = 'The lifetime of the function "{f_name}" expired.' if '_' + self._orig_f_name == self._function.__name__: msg = [msg_patt.format(f_name=self._orig_f_name), 'Please turn off its deprecated version in the configuration'] else: msg = ['Although function "{f_name}" is called, an alias "{f_alias}" ' 'is configured as its deprecated version.'.format( f_name=self._orig_f_name, f_alias=self._with_name or self._orig_f_name), msg_patt.format(f_name=self._with_name or self._orig_f_name), 'Please use its successor "{successor}" instead.'.format(successor=self._orig_f_name)] log.error(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) _decorate.__doc__ = self._function.__doc__ return _decorate with_deprecated = _WithDeprecated def ensure_unicode_args(function): ''' Decodes all arguments passed to the wrapped function ''' @wraps(function) def wrapped(*args, **kwargs): if six.PY2: return function( *salt.utils.data.decode_list(args), **salt.utils.data.decode_dict(kwargs) ) else: return function(*args, **kwargs) return wrapped def external(func): ''' Mark function as external. :param func: :return: ''' def f(*args, **kwargs): ''' Stub. :param args: :param kwargs: :return: ''' return func(*args, **kwargs) f.external = True f.__doc__ = func.__doc__ return f
saltstack/salt
salt/utils/decorators/__init__.py
ensure_unicode_args
python
def ensure_unicode_args(function): ''' Decodes all arguments passed to the wrapped function ''' @wraps(function) def wrapped(*args, **kwargs): if six.PY2: return function( *salt.utils.data.decode_list(args), **salt.utils.data.decode_dict(kwargs) ) else: return function(*args, **kwargs) return wrapped
Decodes all arguments passed to the wrapped function
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L654-L667
null
# -*- coding: utf-8 -*- ''' Helpful decorators for module writing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import errno import inspect import logging import subprocess import sys import time from functools import wraps from collections import defaultdict # Import salt libs import salt.utils.args import salt.utils.data from salt.exceptions import CommandExecutionError, SaltConfigurationError from salt.log import LOG_LEVELS # Import 3rd-party libs from salt.ext import six IS_WINDOWS = False if getattr(sys, 'getwindowsversion', False): IS_WINDOWS = True log = logging.getLogger(__name__) class Depends(object): ''' This decorator will check the module when it is loaded and check that the dependencies passed in are in the globals of the module. If not, it will cause the function to be unloaded (or replaced). ''' # kind -> Dependency -> list of things that depend on it dependency_dict = defaultdict(lambda: defaultdict(dict)) def __init__(self, *dependencies, **kwargs): ''' The decorator is instantiated with a list of dependencies (string of global name) An example use of this would be: .. code-block:: python @depends('modulename') def test(): return 'foo' OR @depends('modulename', fallback_function=function) def test(): return 'foo' .. code-block:: python This can also be done with the retcode of a command, using the ``retcode`` argument: @depends('/opt/bin/check_cmd', retcode=0) def test(): return 'foo' It is also possible to check for any nonzero retcode using the ``nonzero_retcode`` argument: @depends('/opt/bin/check_cmd', nonzero_retcode=True) def test(): return 'foo' .. note:: The command must be formatted as a string, not a list of args. Additionally, I/O redirection and other shell-specific syntax are not supported since this uses shell=False when calling subprocess.Popen(). ''' log.trace( 'Depends decorator instantiated with dep list of %s and kwargs %s', dependencies, kwargs ) self.dependencies = dependencies self.params = kwargs def __call__(self, function): ''' The decorator is "__call__"d with the function, we take that function and determine which module and function name it is to store in the class wide dependency_dict ''' try: # This inspect call may fail under certain conditions in the loader. # Possibly related to a Python bug here: # http://bugs.python.org/issue17735 frame = inspect.stack()[1][0] # due to missing *.py files under esky we cannot use inspect.getmodule # module name is something like salt.loaded.int.modules.test _, kind, mod_name = frame.f_globals['__name__'].rsplit('.', 2) fun_name = function.__name__ for dep in self.dependencies: self.dependency_dict[kind][dep][(mod_name, fun_name)] = (frame, self.params) except Exception as exc: log.exception( 'Exception encountered when attempting to inspect frame in ' 'dependency decorator' ) return function @staticmethod def run_command(dependency, mod_name, func_name): full_name = '{0}.{1}'.format(mod_name, func_name) log.trace('Running \'%s\' for \'%s\'', dependency, full_name) if IS_WINDOWS: args = salt.utils.args.shlex_split(dependency, posix=False) else: args = salt.utils.args.shlex_split(dependency) log.trace('Command after shlex_split: %s', args) proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = proc.communicate()[0] retcode = proc.returncode log.trace('Output from \'%s\': %s', dependency, output) log.trace('Retcode from \'%s\': %d', dependency, retcode) return retcode @classmethod def enforce_dependencies(cls, functions, kind): ''' This is a class global method to enforce the dependencies that you currently know about. It will modify the "functions" dict and remove/replace modules that are missing dependencies. ''' for dependency, dependent_dict in six.iteritems(cls.dependency_dict[kind]): for (mod_name, func_name), (frame, params) in six.iteritems(dependent_dict): if 'retcode' in params or 'nonzero_retcode' in params: try: retcode = cls.run_command(dependency, mod_name, func_name) except OSError as exc: if exc.errno == errno.ENOENT: log.trace( 'Failed to run command %s, %s not found', dependency, exc.filename ) else: log.trace( 'Failed to run command \'%s\': %s', dependency, exc ) retcode = -1 if 'retcode' in params: if params['retcode'] == retcode: continue elif 'nonzero_retcode' in params: if params['nonzero_retcode']: if retcode != 0: continue else: if retcode == 0: continue # check if dependency is loaded elif dependency is True: log.trace( 'Dependency for %s.%s exists, not unloading', mod_name, func_name ) continue # check if you have the dependency elif dependency in frame.f_globals \ or dependency in frame.f_locals: log.trace( 'Dependency (%s) already loaded inside %s, skipping', dependency, mod_name ) continue log.trace( 'Unloading %s.%s because dependency (%s) is not met', mod_name, func_name, dependency ) # if not, unload the function if frame: try: func_name = frame.f_globals['__func_alias__'][func_name] except (AttributeError, KeyError): pass mod_key = '{0}.{1}'.format(mod_name, func_name) # if we don't have this module loaded, skip it! if mod_key not in functions: continue try: fallback_function = params.get('fallback_function') if fallback_function is not None: functions[mod_key] = fallback_function else: del functions[mod_key] except AttributeError: # we already did??? log.trace('%s already removed, skipping', mod_key) continue depends = Depends def timing(function): ''' Decorator wrapper to log execution time, for profiling purposes ''' @wraps(function) def wrapped(*args, **kwargs): start_time = time.time() ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs)) end_time = time.time() if function.__module__.startswith('salt.loaded.int.'): mod_name = function.__module__[16:] else: mod_name = function.__module__ fstr = 'Function %s.%s took %.{0}f seconds to execute'.format( sys.float_info.dig ) log.profile(fstr, mod_name, function.__name__, end_time - start_time) return ret return wrapped def memoize(func): ''' Memoize aka cache the return output of a function given a specific set of arguments .. versionedited:: 2016.3.4 Added **kwargs support. ''' cache = {} @wraps(func) def _memoize(*args, **kwargs): str_args = [] for arg in args: if not isinstance(arg, six.string_types): str_args.append(six.text_type(arg)) else: str_args.append(arg) args_ = ','.join(list(str_args) + ['{0}={1}'.format(k, kwargs[k]) for k in sorted(kwargs)]) if args_ not in cache: cache[args_] = func(*args, **kwargs) return cache[args_] return _memoize class _DeprecationDecorator(object): ''' Base mix-in class for the deprecation decorator. Takes care of a common functionality, used in its derivatives. ''' OPT_IN = 1 OPT_OUT = 2 def __init__(self, globals, version): ''' Constructor. :param globals: Module globals. Important for finding out replacement functions :param version: Expiration version :return: ''' from salt.version import SaltStackVersion, __saltstack_version__ self._globals = globals self._exp_version_name = version self._exp_version = SaltStackVersion.from_name(self._exp_version_name) self._curr_version = __saltstack_version__.info self._raise_later = None self._function = None self._orig_f_name = None def _get_args(self, kwargs): ''' Discard all keywords which aren't function-specific from the kwargs. :param kwargs: :return: ''' _args = list() _kwargs = salt.utils.args.clean_kwargs(**kwargs) return _args, _kwargs def _call_function(self, kwargs): ''' Call target function that has been decorated. :return: ''' if self._raise_later: raise self._raise_later # pylint: disable=E0702 if self._function: args, kwargs = self._get_args(kwargs) try: return self._function(*args, **kwargs) except TypeError as error: error = six.text_type(error).replace(self._function, self._orig_f_name) # Hide hidden functions log.error( 'Function "%s" was not properly called: %s', self._orig_f_name, error ) return self._function.__doc__ except Exception as error: log.error( 'Unhandled exception occurred in function "%s: %s', self._function.__name__, error ) raise error else: raise CommandExecutionError("Function is deprecated, but the successor function was not found.") def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' self._function = function self._orig_f_name = self._function.__name__ class _IsDeprecated(_DeprecationDecorator): ''' This decorator should be used only with the deprecated functions to mark them as deprecated and alter its behavior a corresponding way. The usage is only suitable if deprecation process is renaming the function from one to another. In case function name or even function signature stays the same, please use 'with_deprecated' decorator instead. It has the following functionality: 1. Put a warning level message to the log, informing that the deprecated function has been in use. 2. Raise an exception, if deprecated function is being called, but the lifetime of it already expired. 3. Point to the successor of the deprecated function in the log messages as well during the blocking it, once expired. Usage of this decorator as follows. In this example no successor is mentioned, hence the function "foo()" will be logged with the warning each time is called and blocked completely, once EOF of it is reached: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium") def foo(): pass In the following example a successor function is mentioned, hence every time the function "bar()" is called, message will suggest to use function "baz()" instead. Once EOF is reached of the function "bar()", an exception will ask to use function "baz()", in order to continue: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium", with_successor="baz") def bar(): pass def baz(): pass ''' def __init__(self, globals, version, with_successor=None): ''' Constructor of the decorator 'is_deprecated'. :param globals: Module globals :param version: Version to be deprecated :param with_successor: Successor function (optional) :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._successor = with_successor def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' if self._curr_version < self._exp_version: msg = ['The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format(f_name=self._function.__name__, version_name=self._exp_version_name)] if self._successor: msg.append('Use successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) else: msg = ['The lifetime of the function "{f_name}" expired.'.format(f_name=self._function.__name__)] if self._successor: msg.append('Please use its successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) return _decorate is_deprecated = _IsDeprecated class _WithDeprecated(_DeprecationDecorator): ''' This decorator should be used with the successor functions to mark them as a new and alter its behavior in a corresponding way. It is used alone if a function content or function signature needs to be replaced, leaving the name of the function same. In case function needs to be renamed or just dropped, it has to be used in pair with 'is_deprecated' decorator. It has the following functionality: 1. Put a warning level message to the log, in case a component is using its deprecated version. 2. Switch between old and new function in case an older version is configured for the desired use. 3. Raise an exception, if deprecated version reached EOL and point out for the new version. Usage of this decorator as follows. If 'with_name' is not specified, then the name of the deprecated function is assumed with the "_" prefix. In this case, in order to deprecate a function, it is required: - Add a prefix "_" to an existing function. E.g.: "foo()" to "_foo()". - Implement a new function with exactly the same name, just without the prefix "_". Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium") def foo(): "This is a new function" def _foo(): "This is a deprecated function" In case there is a need to deprecate a function and rename it, the decorator should be used with the 'with_name' parameter. This parameter is pointing to the existing deprecated function. In this case deprecation process as follows: - Leave a deprecated function without changes, as is. - Implement a new function and decorate it with this decorator. - Set a parameter 'with_name' to the deprecated function. - If a new function has a different name than a deprecated, decorate a deprecated function with the 'is_deprecated' decorator in order to let the function have a deprecated behavior. Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium", with_name="an_old_function") def a_new_function(): "This is a new function" @is_deprecated(globals(), "Beryllium", with_successor="a_new_function") def an_old_function(): "This is a deprecated function" ''' MODULE_NAME = '__virtualname__' CFG_USE_DEPRECATED = 'use_deprecated' CFG_USE_SUPERSEDED = 'use_superseded' def __init__(self, globals, version, with_name=None, policy=_DeprecationDecorator.OPT_OUT): ''' Constructor of the decorator 'with_deprecated' :param globals: :param version: :param with_name: :param policy: :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._with_name = with_name self._policy = policy def _set_function(self, function): ''' Based on the configuration, set to execute an old or a new function. :return: ''' full_name = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=function.__name__) if full_name.startswith("."): self._raise_later = CommandExecutionError('Module not found for function "{f_name}"'.format( f_name=function.__name__)) opts = self._globals.get('__opts__', '{}') pillar = self._globals.get('__pillar__', '{}') use_deprecated = (full_name in opts.get(self.CFG_USE_DEPRECATED, list()) or full_name in pillar.get(self.CFG_USE_DEPRECATED, list())) use_superseded = (full_name in opts.get(self.CFG_USE_SUPERSEDED, list()) or full_name in pillar.get(self.CFG_USE_SUPERSEDED, list())) if use_deprecated and use_superseded: raise SaltConfigurationError("Function '{0}' is mentioned both in deprecated " "and superseded sections. Please remove any of that.".format(full_name)) old_function = self._globals.get(self._with_name or "_{0}".format(function.__name__)) if self._policy == self.OPT_IN: self._function = function if use_superseded else old_function else: self._function = old_function if use_deprecated else function def _is_used_deprecated(self): ''' Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return: ''' func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=self._orig_f_name) return func_path in self._globals.get('__opts__').get( self.CFG_USE_DEPRECATED, list()) or func_path in self._globals.get('__pillar__').get( self.CFG_USE_DEPRECATED, list()) or (self._policy == self.OPT_IN and not (func_path in self._globals.get('__opts__', {}).get( self.CFG_USE_SUPERSEDED, list())) and not (func_path in self._globals.get('__pillar__', {}).get( self.CFG_USE_SUPERSEDED, list()))), func_path def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' self._set_function(function) is_deprecated, func_path = self._is_used_deprecated() if is_deprecated: if self._curr_version < self._exp_version: msg = list() if self._with_name: msg.append('The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format( f_name=self._with_name.startswith("_") and self._orig_f_name or self._with_name, version_name=self._exp_version_name)) msg.append('Use its successor "{successor}" instead.'.format(successor=self._orig_f_name)) else: msg.append('The function "{f_name}" is using its deprecated version and will ' 'expire in version "{version_name}".'.format(f_name=func_path, version_name=self._exp_version_name)) log.warning(' '.join(msg)) else: msg_patt = 'The lifetime of the function "{f_name}" expired.' if '_' + self._orig_f_name == self._function.__name__: msg = [msg_patt.format(f_name=self._orig_f_name), 'Please turn off its deprecated version in the configuration'] else: msg = ['Although function "{f_name}" is called, an alias "{f_alias}" ' 'is configured as its deprecated version.'.format( f_name=self._orig_f_name, f_alias=self._with_name or self._orig_f_name), msg_patt.format(f_name=self._with_name or self._orig_f_name), 'Please use its successor "{successor}" instead.'.format(successor=self._orig_f_name)] log.error(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) _decorate.__doc__ = self._function.__doc__ return _decorate with_deprecated = _WithDeprecated def ignores_kwargs(*kwarg_names): ''' Decorator to filter out unexpected keyword arguments from the call kwarg_names: List of argument names to ignore ''' def _ignores_kwargs(fn): def __ignores_kwargs(*args, **kwargs): kwargs_filtered = kwargs.copy() for name in kwarg_names: if name in kwargs_filtered: del kwargs_filtered[name] return fn(*args, **kwargs_filtered) return __ignores_kwargs return _ignores_kwargs def external(func): ''' Mark function as external. :param func: :return: ''' def f(*args, **kwargs): ''' Stub. :param args: :param kwargs: :return: ''' return func(*args, **kwargs) f.external = True f.__doc__ = func.__doc__ return f
saltstack/salt
salt/utils/decorators/__init__.py
external
python
def external(func): ''' Mark function as external. :param func: :return: ''' def f(*args, **kwargs): ''' Stub. :param args: :param kwargs: :return: ''' return func(*args, **kwargs) f.external = True f.__doc__ = func.__doc__ return f
Mark function as external. :param func: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L670-L691
null
# -*- coding: utf-8 -*- ''' Helpful decorators for module writing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import errno import inspect import logging import subprocess import sys import time from functools import wraps from collections import defaultdict # Import salt libs import salt.utils.args import salt.utils.data from salt.exceptions import CommandExecutionError, SaltConfigurationError from salt.log import LOG_LEVELS # Import 3rd-party libs from salt.ext import six IS_WINDOWS = False if getattr(sys, 'getwindowsversion', False): IS_WINDOWS = True log = logging.getLogger(__name__) class Depends(object): ''' This decorator will check the module when it is loaded and check that the dependencies passed in are in the globals of the module. If not, it will cause the function to be unloaded (or replaced). ''' # kind -> Dependency -> list of things that depend on it dependency_dict = defaultdict(lambda: defaultdict(dict)) def __init__(self, *dependencies, **kwargs): ''' The decorator is instantiated with a list of dependencies (string of global name) An example use of this would be: .. code-block:: python @depends('modulename') def test(): return 'foo' OR @depends('modulename', fallback_function=function) def test(): return 'foo' .. code-block:: python This can also be done with the retcode of a command, using the ``retcode`` argument: @depends('/opt/bin/check_cmd', retcode=0) def test(): return 'foo' It is also possible to check for any nonzero retcode using the ``nonzero_retcode`` argument: @depends('/opt/bin/check_cmd', nonzero_retcode=True) def test(): return 'foo' .. note:: The command must be formatted as a string, not a list of args. Additionally, I/O redirection and other shell-specific syntax are not supported since this uses shell=False when calling subprocess.Popen(). ''' log.trace( 'Depends decorator instantiated with dep list of %s and kwargs %s', dependencies, kwargs ) self.dependencies = dependencies self.params = kwargs def __call__(self, function): ''' The decorator is "__call__"d with the function, we take that function and determine which module and function name it is to store in the class wide dependency_dict ''' try: # This inspect call may fail under certain conditions in the loader. # Possibly related to a Python bug here: # http://bugs.python.org/issue17735 frame = inspect.stack()[1][0] # due to missing *.py files under esky we cannot use inspect.getmodule # module name is something like salt.loaded.int.modules.test _, kind, mod_name = frame.f_globals['__name__'].rsplit('.', 2) fun_name = function.__name__ for dep in self.dependencies: self.dependency_dict[kind][dep][(mod_name, fun_name)] = (frame, self.params) except Exception as exc: log.exception( 'Exception encountered when attempting to inspect frame in ' 'dependency decorator' ) return function @staticmethod def run_command(dependency, mod_name, func_name): full_name = '{0}.{1}'.format(mod_name, func_name) log.trace('Running \'%s\' for \'%s\'', dependency, full_name) if IS_WINDOWS: args = salt.utils.args.shlex_split(dependency, posix=False) else: args = salt.utils.args.shlex_split(dependency) log.trace('Command after shlex_split: %s', args) proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = proc.communicate()[0] retcode = proc.returncode log.trace('Output from \'%s\': %s', dependency, output) log.trace('Retcode from \'%s\': %d', dependency, retcode) return retcode @classmethod def enforce_dependencies(cls, functions, kind): ''' This is a class global method to enforce the dependencies that you currently know about. It will modify the "functions" dict and remove/replace modules that are missing dependencies. ''' for dependency, dependent_dict in six.iteritems(cls.dependency_dict[kind]): for (mod_name, func_name), (frame, params) in six.iteritems(dependent_dict): if 'retcode' in params or 'nonzero_retcode' in params: try: retcode = cls.run_command(dependency, mod_name, func_name) except OSError as exc: if exc.errno == errno.ENOENT: log.trace( 'Failed to run command %s, %s not found', dependency, exc.filename ) else: log.trace( 'Failed to run command \'%s\': %s', dependency, exc ) retcode = -1 if 'retcode' in params: if params['retcode'] == retcode: continue elif 'nonzero_retcode' in params: if params['nonzero_retcode']: if retcode != 0: continue else: if retcode == 0: continue # check if dependency is loaded elif dependency is True: log.trace( 'Dependency for %s.%s exists, not unloading', mod_name, func_name ) continue # check if you have the dependency elif dependency in frame.f_globals \ or dependency in frame.f_locals: log.trace( 'Dependency (%s) already loaded inside %s, skipping', dependency, mod_name ) continue log.trace( 'Unloading %s.%s because dependency (%s) is not met', mod_name, func_name, dependency ) # if not, unload the function if frame: try: func_name = frame.f_globals['__func_alias__'][func_name] except (AttributeError, KeyError): pass mod_key = '{0}.{1}'.format(mod_name, func_name) # if we don't have this module loaded, skip it! if mod_key not in functions: continue try: fallback_function = params.get('fallback_function') if fallback_function is not None: functions[mod_key] = fallback_function else: del functions[mod_key] except AttributeError: # we already did??? log.trace('%s already removed, skipping', mod_key) continue depends = Depends def timing(function): ''' Decorator wrapper to log execution time, for profiling purposes ''' @wraps(function) def wrapped(*args, **kwargs): start_time = time.time() ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs)) end_time = time.time() if function.__module__.startswith('salt.loaded.int.'): mod_name = function.__module__[16:] else: mod_name = function.__module__ fstr = 'Function %s.%s took %.{0}f seconds to execute'.format( sys.float_info.dig ) log.profile(fstr, mod_name, function.__name__, end_time - start_time) return ret return wrapped def memoize(func): ''' Memoize aka cache the return output of a function given a specific set of arguments .. versionedited:: 2016.3.4 Added **kwargs support. ''' cache = {} @wraps(func) def _memoize(*args, **kwargs): str_args = [] for arg in args: if not isinstance(arg, six.string_types): str_args.append(six.text_type(arg)) else: str_args.append(arg) args_ = ','.join(list(str_args) + ['{0}={1}'.format(k, kwargs[k]) for k in sorted(kwargs)]) if args_ not in cache: cache[args_] = func(*args, **kwargs) return cache[args_] return _memoize class _DeprecationDecorator(object): ''' Base mix-in class for the deprecation decorator. Takes care of a common functionality, used in its derivatives. ''' OPT_IN = 1 OPT_OUT = 2 def __init__(self, globals, version): ''' Constructor. :param globals: Module globals. Important for finding out replacement functions :param version: Expiration version :return: ''' from salt.version import SaltStackVersion, __saltstack_version__ self._globals = globals self._exp_version_name = version self._exp_version = SaltStackVersion.from_name(self._exp_version_name) self._curr_version = __saltstack_version__.info self._raise_later = None self._function = None self._orig_f_name = None def _get_args(self, kwargs): ''' Discard all keywords which aren't function-specific from the kwargs. :param kwargs: :return: ''' _args = list() _kwargs = salt.utils.args.clean_kwargs(**kwargs) return _args, _kwargs def _call_function(self, kwargs): ''' Call target function that has been decorated. :return: ''' if self._raise_later: raise self._raise_later # pylint: disable=E0702 if self._function: args, kwargs = self._get_args(kwargs) try: return self._function(*args, **kwargs) except TypeError as error: error = six.text_type(error).replace(self._function, self._orig_f_name) # Hide hidden functions log.error( 'Function "%s" was not properly called: %s', self._orig_f_name, error ) return self._function.__doc__ except Exception as error: log.error( 'Unhandled exception occurred in function "%s: %s', self._function.__name__, error ) raise error else: raise CommandExecutionError("Function is deprecated, but the successor function was not found.") def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' self._function = function self._orig_f_name = self._function.__name__ class _IsDeprecated(_DeprecationDecorator): ''' This decorator should be used only with the deprecated functions to mark them as deprecated and alter its behavior a corresponding way. The usage is only suitable if deprecation process is renaming the function from one to another. In case function name or even function signature stays the same, please use 'with_deprecated' decorator instead. It has the following functionality: 1. Put a warning level message to the log, informing that the deprecated function has been in use. 2. Raise an exception, if deprecated function is being called, but the lifetime of it already expired. 3. Point to the successor of the deprecated function in the log messages as well during the blocking it, once expired. Usage of this decorator as follows. In this example no successor is mentioned, hence the function "foo()" will be logged with the warning each time is called and blocked completely, once EOF of it is reached: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium") def foo(): pass In the following example a successor function is mentioned, hence every time the function "bar()" is called, message will suggest to use function "baz()" instead. Once EOF is reached of the function "bar()", an exception will ask to use function "baz()", in order to continue: from salt.util.decorators import is_deprecated @is_deprecated(globals(), "Beryllium", with_successor="baz") def bar(): pass def baz(): pass ''' def __init__(self, globals, version, with_successor=None): ''' Constructor of the decorator 'is_deprecated'. :param globals: Module globals :param version: Version to be deprecated :param with_successor: Successor function (optional) :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._successor = with_successor def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' if self._curr_version < self._exp_version: msg = ['The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format(f_name=self._function.__name__, version_name=self._exp_version_name)] if self._successor: msg.append('Use successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) else: msg = ['The lifetime of the function "{f_name}" expired.'.format(f_name=self._function.__name__)] if self._successor: msg.append('Please use its successor "{successor}" instead.'.format(successor=self._successor)) log.warning(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) return _decorate is_deprecated = _IsDeprecated class _WithDeprecated(_DeprecationDecorator): ''' This decorator should be used with the successor functions to mark them as a new and alter its behavior in a corresponding way. It is used alone if a function content or function signature needs to be replaced, leaving the name of the function same. In case function needs to be renamed or just dropped, it has to be used in pair with 'is_deprecated' decorator. It has the following functionality: 1. Put a warning level message to the log, in case a component is using its deprecated version. 2. Switch between old and new function in case an older version is configured for the desired use. 3. Raise an exception, if deprecated version reached EOL and point out for the new version. Usage of this decorator as follows. If 'with_name' is not specified, then the name of the deprecated function is assumed with the "_" prefix. In this case, in order to deprecate a function, it is required: - Add a prefix "_" to an existing function. E.g.: "foo()" to "_foo()". - Implement a new function with exactly the same name, just without the prefix "_". Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium") def foo(): "This is a new function" def _foo(): "This is a deprecated function" In case there is a need to deprecate a function and rename it, the decorator should be used with the 'with_name' parameter. This parameter is pointing to the existing deprecated function. In this case deprecation process as follows: - Leave a deprecated function without changes, as is. - Implement a new function and decorate it with this decorator. - Set a parameter 'with_name' to the deprecated function. - If a new function has a different name than a deprecated, decorate a deprecated function with the 'is_deprecated' decorator in order to let the function have a deprecated behavior. Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium", with_name="an_old_function") def a_new_function(): "This is a new function" @is_deprecated(globals(), "Beryllium", with_successor="a_new_function") def an_old_function(): "This is a deprecated function" ''' MODULE_NAME = '__virtualname__' CFG_USE_DEPRECATED = 'use_deprecated' CFG_USE_SUPERSEDED = 'use_superseded' def __init__(self, globals, version, with_name=None, policy=_DeprecationDecorator.OPT_OUT): ''' Constructor of the decorator 'with_deprecated' :param globals: :param version: :param with_name: :param policy: :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._with_name = with_name self._policy = policy def _set_function(self, function): ''' Based on the configuration, set to execute an old or a new function. :return: ''' full_name = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=function.__name__) if full_name.startswith("."): self._raise_later = CommandExecutionError('Module not found for function "{f_name}"'.format( f_name=function.__name__)) opts = self._globals.get('__opts__', '{}') pillar = self._globals.get('__pillar__', '{}') use_deprecated = (full_name in opts.get(self.CFG_USE_DEPRECATED, list()) or full_name in pillar.get(self.CFG_USE_DEPRECATED, list())) use_superseded = (full_name in opts.get(self.CFG_USE_SUPERSEDED, list()) or full_name in pillar.get(self.CFG_USE_SUPERSEDED, list())) if use_deprecated and use_superseded: raise SaltConfigurationError("Function '{0}' is mentioned both in deprecated " "and superseded sections. Please remove any of that.".format(full_name)) old_function = self._globals.get(self._with_name or "_{0}".format(function.__name__)) if self._policy == self.OPT_IN: self._function = function if use_superseded else old_function else: self._function = old_function if use_deprecated else function def _is_used_deprecated(self): ''' Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return: ''' func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=self._orig_f_name) return func_path in self._globals.get('__opts__').get( self.CFG_USE_DEPRECATED, list()) or func_path in self._globals.get('__pillar__').get( self.CFG_USE_DEPRECATED, list()) or (self._policy == self.OPT_IN and not (func_path in self._globals.get('__opts__', {}).get( self.CFG_USE_SUPERSEDED, list())) and not (func_path in self._globals.get('__pillar__', {}).get( self.CFG_USE_SUPERSEDED, list()))), func_path def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' self._set_function(function) is_deprecated, func_path = self._is_used_deprecated() if is_deprecated: if self._curr_version < self._exp_version: msg = list() if self._with_name: msg.append('The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format( f_name=self._with_name.startswith("_") and self._orig_f_name or self._with_name, version_name=self._exp_version_name)) msg.append('Use its successor "{successor}" instead.'.format(successor=self._orig_f_name)) else: msg.append('The function "{f_name}" is using its deprecated version and will ' 'expire in version "{version_name}".'.format(f_name=func_path, version_name=self._exp_version_name)) log.warning(' '.join(msg)) else: msg_patt = 'The lifetime of the function "{f_name}" expired.' if '_' + self._orig_f_name == self._function.__name__: msg = [msg_patt.format(f_name=self._orig_f_name), 'Please turn off its deprecated version in the configuration'] else: msg = ['Although function "{f_name}" is called, an alias "{f_alias}" ' 'is configured as its deprecated version.'.format( f_name=self._orig_f_name, f_alias=self._with_name or self._orig_f_name), msg_patt.format(f_name=self._with_name or self._orig_f_name), 'Please use its successor "{successor}" instead.'.format(successor=self._orig_f_name)] log.error(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) _decorate.__doc__ = self._function.__doc__ return _decorate with_deprecated = _WithDeprecated def ignores_kwargs(*kwarg_names): ''' Decorator to filter out unexpected keyword arguments from the call kwarg_names: List of argument names to ignore ''' def _ignores_kwargs(fn): def __ignores_kwargs(*args, **kwargs): kwargs_filtered = kwargs.copy() for name in kwarg_names: if name in kwargs_filtered: del kwargs_filtered[name] return fn(*args, **kwargs_filtered) return __ignores_kwargs return _ignores_kwargs def ensure_unicode_args(function): ''' Decodes all arguments passed to the wrapped function ''' @wraps(function) def wrapped(*args, **kwargs): if six.PY2: return function( *salt.utils.data.decode_list(args), **salt.utils.data.decode_dict(kwargs) ) else: return function(*args, **kwargs) return wrapped
saltstack/salt
salt/utils/decorators/__init__.py
Depends.enforce_dependencies
python
def enforce_dependencies(cls, functions, kind): ''' This is a class global method to enforce the dependencies that you currently know about. It will modify the "functions" dict and remove/replace modules that are missing dependencies. ''' for dependency, dependent_dict in six.iteritems(cls.dependency_dict[kind]): for (mod_name, func_name), (frame, params) in six.iteritems(dependent_dict): if 'retcode' in params or 'nonzero_retcode' in params: try: retcode = cls.run_command(dependency, mod_name, func_name) except OSError as exc: if exc.errno == errno.ENOENT: log.trace( 'Failed to run command %s, %s not found', dependency, exc.filename ) else: log.trace( 'Failed to run command \'%s\': %s', dependency, exc ) retcode = -1 if 'retcode' in params: if params['retcode'] == retcode: continue elif 'nonzero_retcode' in params: if params['nonzero_retcode']: if retcode != 0: continue else: if retcode == 0: continue # check if dependency is loaded elif dependency is True: log.trace( 'Dependency for %s.%s exists, not unloading', mod_name, func_name ) continue # check if you have the dependency elif dependency in frame.f_globals \ or dependency in frame.f_locals: log.trace( 'Dependency (%s) already loaded inside %s, skipping', dependency, mod_name ) continue log.trace( 'Unloading %s.%s because dependency (%s) is not met', mod_name, func_name, dependency ) # if not, unload the function if frame: try: func_name = frame.f_globals['__func_alias__'][func_name] except (AttributeError, KeyError): pass mod_key = '{0}.{1}'.format(mod_name, func_name) # if we don't have this module loaded, skip it! if mod_key not in functions: continue try: fallback_function = params.get('fallback_function') if fallback_function is not None: functions[mod_key] = fallback_function else: del functions[mod_key] except AttributeError: # we already did??? log.trace('%s already removed, skipping', mod_key) continue
This is a class global method to enforce the dependencies that you currently know about. It will modify the "functions" dict and remove/replace modules that are missing dependencies.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L135-L214
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
class Depends(object): ''' This decorator will check the module when it is loaded and check that the dependencies passed in are in the globals of the module. If not, it will cause the function to be unloaded (or replaced). ''' # kind -> Dependency -> list of things that depend on it dependency_dict = defaultdict(lambda: defaultdict(dict)) def __init__(self, *dependencies, **kwargs): ''' The decorator is instantiated with a list of dependencies (string of global name) An example use of this would be: .. code-block:: python @depends('modulename') def test(): return 'foo' OR @depends('modulename', fallback_function=function) def test(): return 'foo' .. code-block:: python This can also be done with the retcode of a command, using the ``retcode`` argument: @depends('/opt/bin/check_cmd', retcode=0) def test(): return 'foo' It is also possible to check for any nonzero retcode using the ``nonzero_retcode`` argument: @depends('/opt/bin/check_cmd', nonzero_retcode=True) def test(): return 'foo' .. note:: The command must be formatted as a string, not a list of args. Additionally, I/O redirection and other shell-specific syntax are not supported since this uses shell=False when calling subprocess.Popen(). ''' log.trace( 'Depends decorator instantiated with dep list of %s and kwargs %s', dependencies, kwargs ) self.dependencies = dependencies self.params = kwargs def __call__(self, function): ''' The decorator is "__call__"d with the function, we take that function and determine which module and function name it is to store in the class wide dependency_dict ''' try: # This inspect call may fail under certain conditions in the loader. # Possibly related to a Python bug here: # http://bugs.python.org/issue17735 frame = inspect.stack()[1][0] # due to missing *.py files under esky we cannot use inspect.getmodule # module name is something like salt.loaded.int.modules.test _, kind, mod_name = frame.f_globals['__name__'].rsplit('.', 2) fun_name = function.__name__ for dep in self.dependencies: self.dependency_dict[kind][dep][(mod_name, fun_name)] = (frame, self.params) except Exception as exc: log.exception( 'Exception encountered when attempting to inspect frame in ' 'dependency decorator' ) return function @staticmethod def run_command(dependency, mod_name, func_name): full_name = '{0}.{1}'.format(mod_name, func_name) log.trace('Running \'%s\' for \'%s\'', dependency, full_name) if IS_WINDOWS: args = salt.utils.args.shlex_split(dependency, posix=False) else: args = salt.utils.args.shlex_split(dependency) log.trace('Command after shlex_split: %s', args) proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = proc.communicate()[0] retcode = proc.returncode log.trace('Output from \'%s\': %s', dependency, output) log.trace('Retcode from \'%s\': %d', dependency, retcode) return retcode @classmethod
saltstack/salt
salt/utils/decorators/__init__.py
_DeprecationDecorator._get_args
python
def _get_args(self, kwargs): ''' Discard all keywords which aren't function-specific from the kwargs. :param kwargs: :return: ''' _args = list() _kwargs = salt.utils.args.clean_kwargs(**kwargs) return _args, _kwargs
Discard all keywords which aren't function-specific from the kwargs. :param kwargs: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L295-L305
null
class _DeprecationDecorator(object): ''' Base mix-in class for the deprecation decorator. Takes care of a common functionality, used in its derivatives. ''' OPT_IN = 1 OPT_OUT = 2 def __init__(self, globals, version): ''' Constructor. :param globals: Module globals. Important for finding out replacement functions :param version: Expiration version :return: ''' from salt.version import SaltStackVersion, __saltstack_version__ self._globals = globals self._exp_version_name = version self._exp_version = SaltStackVersion.from_name(self._exp_version_name) self._curr_version = __saltstack_version__.info self._raise_later = None self._function = None self._orig_f_name = None def _call_function(self, kwargs): ''' Call target function that has been decorated. :return: ''' if self._raise_later: raise self._raise_later # pylint: disable=E0702 if self._function: args, kwargs = self._get_args(kwargs) try: return self._function(*args, **kwargs) except TypeError as error: error = six.text_type(error).replace(self._function, self._orig_f_name) # Hide hidden functions log.error( 'Function "%s" was not properly called: %s', self._orig_f_name, error ) return self._function.__doc__ except Exception as error: log.error( 'Unhandled exception occurred in function "%s: %s', self._function.__name__, error ) raise error else: raise CommandExecutionError("Function is deprecated, but the successor function was not found.") def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' self._function = function self._orig_f_name = self._function.__name__
saltstack/salt
salt/utils/decorators/__init__.py
_DeprecationDecorator._call_function
python
def _call_function(self, kwargs): ''' Call target function that has been decorated. :return: ''' if self._raise_later: raise self._raise_later # pylint: disable=E0702 if self._function: args, kwargs = self._get_args(kwargs) try: return self._function(*args, **kwargs) except TypeError as error: error = six.text_type(error).replace(self._function, self._orig_f_name) # Hide hidden functions log.error( 'Function "%s" was not properly called: %s', self._orig_f_name, error ) return self._function.__doc__ except Exception as error: log.error( 'Unhandled exception occurred in function "%s: %s', self._function.__name__, error ) raise error else: raise CommandExecutionError("Function is deprecated, but the successor function was not found.")
Call target function that has been decorated. :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L307-L334
null
class _DeprecationDecorator(object): ''' Base mix-in class for the deprecation decorator. Takes care of a common functionality, used in its derivatives. ''' OPT_IN = 1 OPT_OUT = 2 def __init__(self, globals, version): ''' Constructor. :param globals: Module globals. Important for finding out replacement functions :param version: Expiration version :return: ''' from salt.version import SaltStackVersion, __saltstack_version__ self._globals = globals self._exp_version_name = version self._exp_version = SaltStackVersion.from_name(self._exp_version_name) self._curr_version = __saltstack_version__.info self._raise_later = None self._function = None self._orig_f_name = None def _get_args(self, kwargs): ''' Discard all keywords which aren't function-specific from the kwargs. :param kwargs: :return: ''' _args = list() _kwargs = salt.utils.args.clean_kwargs(**kwargs) return _args, _kwargs def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' self._function = function self._orig_f_name = self._function.__name__
saltstack/salt
salt/utils/decorators/__init__.py
_WithDeprecated._set_function
python
def _set_function(self, function): ''' Based on the configuration, set to execute an old or a new function. :return: ''' full_name = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=function.__name__) if full_name.startswith("."): self._raise_later = CommandExecutionError('Module not found for function "{f_name}"'.format( f_name=function.__name__)) opts = self._globals.get('__opts__', '{}') pillar = self._globals.get('__pillar__', '{}') use_deprecated = (full_name in opts.get(self.CFG_USE_DEPRECATED, list()) or full_name in pillar.get(self.CFG_USE_DEPRECATED, list())) use_superseded = (full_name in opts.get(self.CFG_USE_SUPERSEDED, list()) or full_name in pillar.get(self.CFG_USE_SUPERSEDED, list())) if use_deprecated and use_superseded: raise SaltConfigurationError("Function '{0}' is mentioned both in deprecated " "and superseded sections. Please remove any of that.".format(full_name)) old_function = self._globals.get(self._with_name or "_{0}".format(function.__name__)) if self._policy == self.OPT_IN: self._function = function if use_superseded else old_function else: self._function = old_function if use_deprecated else function
Based on the configuration, set to execute an old or a new function. :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L531-L559
null
class _WithDeprecated(_DeprecationDecorator): ''' This decorator should be used with the successor functions to mark them as a new and alter its behavior in a corresponding way. It is used alone if a function content or function signature needs to be replaced, leaving the name of the function same. In case function needs to be renamed or just dropped, it has to be used in pair with 'is_deprecated' decorator. It has the following functionality: 1. Put a warning level message to the log, in case a component is using its deprecated version. 2. Switch between old and new function in case an older version is configured for the desired use. 3. Raise an exception, if deprecated version reached EOL and point out for the new version. Usage of this decorator as follows. If 'with_name' is not specified, then the name of the deprecated function is assumed with the "_" prefix. In this case, in order to deprecate a function, it is required: - Add a prefix "_" to an existing function. E.g.: "foo()" to "_foo()". - Implement a new function with exactly the same name, just without the prefix "_". Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium") def foo(): "This is a new function" def _foo(): "This is a deprecated function" In case there is a need to deprecate a function and rename it, the decorator should be used with the 'with_name' parameter. This parameter is pointing to the existing deprecated function. In this case deprecation process as follows: - Leave a deprecated function without changes, as is. - Implement a new function and decorate it with this decorator. - Set a parameter 'with_name' to the deprecated function. - If a new function has a different name than a deprecated, decorate a deprecated function with the 'is_deprecated' decorator in order to let the function have a deprecated behavior. Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium", with_name="an_old_function") def a_new_function(): "This is a new function" @is_deprecated(globals(), "Beryllium", with_successor="a_new_function") def an_old_function(): "This is a deprecated function" ''' MODULE_NAME = '__virtualname__' CFG_USE_DEPRECATED = 'use_deprecated' CFG_USE_SUPERSEDED = 'use_superseded' def __init__(self, globals, version, with_name=None, policy=_DeprecationDecorator.OPT_OUT): ''' Constructor of the decorator 'with_deprecated' :param globals: :param version: :param with_name: :param policy: :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._with_name = with_name self._policy = policy def _is_used_deprecated(self): ''' Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return: ''' func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=self._orig_f_name) return func_path in self._globals.get('__opts__').get( self.CFG_USE_DEPRECATED, list()) or func_path in self._globals.get('__pillar__').get( self.CFG_USE_DEPRECATED, list()) or (self._policy == self.OPT_IN and not (func_path in self._globals.get('__opts__', {}).get( self.CFG_USE_SUPERSEDED, list())) and not (func_path in self._globals.get('__pillar__', {}).get( self.CFG_USE_SUPERSEDED, list()))), func_path def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' self._set_function(function) is_deprecated, func_path = self._is_used_deprecated() if is_deprecated: if self._curr_version < self._exp_version: msg = list() if self._with_name: msg.append('The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format( f_name=self._with_name.startswith("_") and self._orig_f_name or self._with_name, version_name=self._exp_version_name)) msg.append('Use its successor "{successor}" instead.'.format(successor=self._orig_f_name)) else: msg.append('The function "{f_name}" is using its deprecated version and will ' 'expire in version "{version_name}".'.format(f_name=func_path, version_name=self._exp_version_name)) log.warning(' '.join(msg)) else: msg_patt = 'The lifetime of the function "{f_name}" expired.' if '_' + self._orig_f_name == self._function.__name__: msg = [msg_patt.format(f_name=self._orig_f_name), 'Please turn off its deprecated version in the configuration'] else: msg = ['Although function "{f_name}" is called, an alias "{f_alias}" ' 'is configured as its deprecated version.'.format( f_name=self._orig_f_name, f_alias=self._with_name or self._orig_f_name), msg_patt.format(f_name=self._with_name or self._orig_f_name), 'Please use its successor "{successor}" instead.'.format(successor=self._orig_f_name)] log.error(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) _decorate.__doc__ = self._function.__doc__ return _decorate
saltstack/salt
salt/utils/decorators/__init__.py
_WithDeprecated._is_used_deprecated
python
def _is_used_deprecated(self): ''' Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return: ''' func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=self._orig_f_name) return func_path in self._globals.get('__opts__').get( self.CFG_USE_DEPRECATED, list()) or func_path in self._globals.get('__pillar__').get( self.CFG_USE_DEPRECATED, list()) or (self._policy == self.OPT_IN and not (func_path in self._globals.get('__opts__', {}).get( self.CFG_USE_SUPERSEDED, list())) and not (func_path in self._globals.get('__pillar__', {}).get( self.CFG_USE_SUPERSEDED, list()))), func_path
Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L561-L578
null
class _WithDeprecated(_DeprecationDecorator): ''' This decorator should be used with the successor functions to mark them as a new and alter its behavior in a corresponding way. It is used alone if a function content or function signature needs to be replaced, leaving the name of the function same. In case function needs to be renamed or just dropped, it has to be used in pair with 'is_deprecated' decorator. It has the following functionality: 1. Put a warning level message to the log, in case a component is using its deprecated version. 2. Switch between old and new function in case an older version is configured for the desired use. 3. Raise an exception, if deprecated version reached EOL and point out for the new version. Usage of this decorator as follows. If 'with_name' is not specified, then the name of the deprecated function is assumed with the "_" prefix. In this case, in order to deprecate a function, it is required: - Add a prefix "_" to an existing function. E.g.: "foo()" to "_foo()". - Implement a new function with exactly the same name, just without the prefix "_". Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium") def foo(): "This is a new function" def _foo(): "This is a deprecated function" In case there is a need to deprecate a function and rename it, the decorator should be used with the 'with_name' parameter. This parameter is pointing to the existing deprecated function. In this case deprecation process as follows: - Leave a deprecated function without changes, as is. - Implement a new function and decorate it with this decorator. - Set a parameter 'with_name' to the deprecated function. - If a new function has a different name than a deprecated, decorate a deprecated function with the 'is_deprecated' decorator in order to let the function have a deprecated behavior. Example: from salt.util.decorators import with_deprecated @with_deprecated(globals(), "Beryllium", with_name="an_old_function") def a_new_function(): "This is a new function" @is_deprecated(globals(), "Beryllium", with_successor="a_new_function") def an_old_function(): "This is a deprecated function" ''' MODULE_NAME = '__virtualname__' CFG_USE_DEPRECATED = 'use_deprecated' CFG_USE_SUPERSEDED = 'use_superseded' def __init__(self, globals, version, with_name=None, policy=_DeprecationDecorator.OPT_OUT): ''' Constructor of the decorator 'with_deprecated' :param globals: :param version: :param with_name: :param policy: :return: ''' _DeprecationDecorator.__init__(self, globals, version) self._with_name = with_name self._policy = policy def _set_function(self, function): ''' Based on the configuration, set to execute an old or a new function. :return: ''' full_name = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[-1], f_name=function.__name__) if full_name.startswith("."): self._raise_later = CommandExecutionError('Module not found for function "{f_name}"'.format( f_name=function.__name__)) opts = self._globals.get('__opts__', '{}') pillar = self._globals.get('__pillar__', '{}') use_deprecated = (full_name in opts.get(self.CFG_USE_DEPRECATED, list()) or full_name in pillar.get(self.CFG_USE_DEPRECATED, list())) use_superseded = (full_name in opts.get(self.CFG_USE_SUPERSEDED, list()) or full_name in pillar.get(self.CFG_USE_SUPERSEDED, list())) if use_deprecated and use_superseded: raise SaltConfigurationError("Function '{0}' is mentioned both in deprecated " "and superseded sections. Please remove any of that.".format(full_name)) old_function = self._globals.get(self._with_name or "_{0}".format(function.__name__)) if self._policy == self.OPT_IN: self._function = function if use_superseded else old_function else: self._function = old_function if use_deprecated else function def __call__(self, function): ''' Callable method of the decorator object when the decorated function is gets called. :param function: :return: ''' _DeprecationDecorator.__call__(self, function) def _decorate(*args, **kwargs): ''' Decorator function. :param args: :param kwargs: :return: ''' self._set_function(function) is_deprecated, func_path = self._is_used_deprecated() if is_deprecated: if self._curr_version < self._exp_version: msg = list() if self._with_name: msg.append('The function "{f_name}" is deprecated and will ' 'expire in version "{version_name}".'.format( f_name=self._with_name.startswith("_") and self._orig_f_name or self._with_name, version_name=self._exp_version_name)) msg.append('Use its successor "{successor}" instead.'.format(successor=self._orig_f_name)) else: msg.append('The function "{f_name}" is using its deprecated version and will ' 'expire in version "{version_name}".'.format(f_name=func_path, version_name=self._exp_version_name)) log.warning(' '.join(msg)) else: msg_patt = 'The lifetime of the function "{f_name}" expired.' if '_' + self._orig_f_name == self._function.__name__: msg = [msg_patt.format(f_name=self._orig_f_name), 'Please turn off its deprecated version in the configuration'] else: msg = ['Although function "{f_name}" is called, an alias "{f_alias}" ' 'is configured as its deprecated version.'.format( f_name=self._orig_f_name, f_alias=self._with_name or self._orig_f_name), msg_patt.format(f_name=self._with_name or self._orig_f_name), 'Please use its successor "{successor}" instead.'.format(successor=self._orig_f_name)] log.error(' '.join(msg)) raise CommandExecutionError(' '.join(msg)) return self._call_function(kwargs) _decorate.__doc__ = self._function.__doc__ return _decorate
saltstack/salt
salt/tops/mongo.py
top
python
def top(**kwargs): ''' Connect to a mongo database and read per-node tops data. Parameters: * `collection`: The mongodb collection to read data from. Defaults to ``'tops'``. * `id_field`: The field in the collection that represents an individual minion id. Defaults to ``'_id'``. * `re_pattern`: If your naming convention in the collection is shorter than the minion id, you can use this to trim the name. `re_pattern` will be used to match the name, and `re_replace` will be used to replace it. Backrefs are supported as they are in the Python standard library. If ``None``, no mangling of the name will be performed - the collection will be searched with the entire minion id. Defaults to ``None``. * `re_replace`: Use as the replacement value in node ids matched with `re_pattern`. Defaults to ''. Feel free to use backreferences here. * `states_field`: The name of the field providing a list of states. * `environment_field`: The name of the field providing the environment. Defaults to ``environment``. ''' host = __opts__['mongo.host'] port = __opts__['mongo.port'] collection = __opts__['master_tops']['mongo'].get('collection', 'tops') id_field = __opts__['master_tops']['mongo'].get('id_field', '_id') re_pattern = __opts__['master_tops']['mongo'].get('re_pattern', '') re_replace = __opts__['master_tops']['mongo'].get('re_replace', '') states_field = __opts__['master_tops']['mongo'].get('states_field', 'states') environment_field = __opts__['master_tops']['mongo'].get('environment_field', 'environment') log.info('connecting to %s:%s for mongo ext_tops', host, port) conn = pymongo.MongoClient(host, port) log.debug('using database \'%s\'', __opts__['mongo.db']) mdb = conn[__opts__['mongo.db']] user = __opts__.get('mongo.user') password = __opts__.get('mongo.password') if user and password: log.debug('authenticating as \'%s\'', user) mdb.authenticate(user, password) # Do the regex string replacement on the minion id minion_id = kwargs['opts']['id'] if re_pattern: minion_id = re.sub(re_pattern, re_replace, minion_id) log.info( 'ext_tops.mongo: looking up tops def for {\'%s\': \'%s\'} in mongo', id_field, minion_id ) result = mdb[collection].find_one({id_field: minion_id}, projection=[states_field, environment_field]) if result and states_field in result: if environment_field in result: environment = result[environment_field] else: environment = 'base' log.debug('ext_tops.mongo: found document, returning states') return {environment: result[states_field]} else: # If we can't find the minion the database it's not necessarily an # error. log.debug('ext_tops.mongo: no document found in collection %s', collection) return {}
Connect to a mongo database and read per-node tops data. Parameters: * `collection`: The mongodb collection to read data from. Defaults to ``'tops'``. * `id_field`: The field in the collection that represents an individual minion id. Defaults to ``'_id'``. * `re_pattern`: If your naming convention in the collection is shorter than the minion id, you can use this to trim the name. `re_pattern` will be used to match the name, and `re_replace` will be used to replace it. Backrefs are supported as they are in the Python standard library. If ``None``, no mangling of the name will be performed - the collection will be searched with the entire minion id. Defaults to ``None``. * `re_replace`: Use as the replacement value in node ids matched with `re_pattern`. Defaults to ''. Feel free to use backreferences here. * `states_field`: The name of the field providing a list of states. * `environment_field`: The name of the field providing the environment. Defaults to ``environment``.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tops/mongo.py#L75-L141
null
# -*- coding: utf-8 -*- ''' Read tops data from a mongodb collection This module will load tops data from a mongo collection. It uses the node's id for lookups. Salt Master Mongo Configuration =============================== The module shares the same base mongo connection variables as :py:mod:`salt.returners.mongo_return`. These variables go in your master config file. * ``mongo.db`` - The mongo database to connect to. Defaults to ``'salt'``. * ``mongo.host`` - The mongo host to connect to. Supports replica sets by specifying all hosts in the set, comma-delimited. Defaults to ``'salt'``. * ``mongo.port`` - The port that the mongo database is running on. Defaults to ``27017``. * ``mongo.user`` - The username for connecting to mongo. Only required if you are using mongo authentication. Defaults to ``''``. * ``mongo.password`` - The password for connecting to mongo. Only required if you are using mongo authentication. Defaults to ``''``. Configuring the Mongo Tops Subsystem ==================================== .. code-block:: yaml master_tops: mongo: collection: tops id_field: _id re_replace: "" re_pattern: \\.example\\.com states_field: states environment_field: environment Module Documentation ==================== ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import re # Import third party libs try: import pymongo HAS_PYMONGO = True except ImportError: HAS_PYMONGO = False __opts__ = {'mongo.db': 'salt', 'mongo.host': 'salt', 'mongo.password': '', 'mongo.port': 27017, 'mongo.user': ''} def __virtual__(): if not HAS_PYMONGO: return False return 'mongo' # Set up logging log = logging.getLogger(__name__)
saltstack/salt
salt/modules/gentoolkitmod.py
revdep_rebuild
python
def revdep_rebuild(lib=None): ''' Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild ''' cmd = 'revdep-rebuild -i --quiet --no-progress' if lib is not None: cmd += ' --library={0}'.format(lib) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoolkitmod.py#L33-L51
null
# -*- coding: utf-8 -*- ''' Support for Gentoolkit ''' from __future__ import absolute_import, print_function, unicode_literals import os HAS_GENTOOLKIT = False # Import third party libs try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod HAS_GENTOOLKIT = True except ImportError: pass # Define the module's virtual name __virtualname__ = 'gentoolkit' def __virtual__(): ''' Only work on Gentoo systems with gentoolkit installed ''' if __grains__['os_family'] == 'Gentoo' and HAS_GENTOOLKIT: return __virtualname__ return (False, 'The gentoolkitmod execution module cannot be loaded: ' 'either the system is not Gentoo or the gentoolkit.eclean python module not available') def _pretty_size(size): ''' Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1]) def _parse_exclude(exclude_file): ''' Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile ''' if os.path.isfile(exclude_file): exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None) else: exclude = dict() return exclude def eclean_dist(destructive=False, package_names=False, size_limit=0, time_limit=0, fetch_restricted=False, exclude_file='/etc/eclean/distfiles.exclude'): ''' Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) if size_limit != 0: size_limit = cli.parseSize(size_limit) clean_size = 0 engine = search.DistfilesSearch(lambda x: None) clean_me, saved, deprecated = engine.findDistfiles( destructive=destructive, package_names=package_names, size_limit=size_limit, time_limit=time_limit, fetch_restricted=fetch_restricted, exclude=exclude) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_dist(clean_me) ret = {'cleaned': cleaned, 'saved': saved, 'deprecated': deprecated, 'total_cleaned': _pretty_size(clean_size)} return ret def eclean_pkg(destructive=False, package_names=False, time_limit=0, exclude_file='/etc/eclean/packages.exclude'): ''' Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) clean_size = 0 # findPackages requires one arg, but does nothing with it. # So we will just pass None in for the required arg clean_me = search.findPackages(None, destructive=destructive, package_names=package_names, time_limit=time_limit, exclude=exclude, pkgdir=search.pkgdir) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_pkgs(clean_me, search.pkgdir) ret = {'cleaned': cleaned, 'total_cleaned': _pretty_size(clean_size)} return ret def _glsa_list_process_output(output): ''' Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs ''' ret = dict() for line in output: try: glsa_id, status, desc = line.split(None, 2) if 'U' in status: status += ' Not Affected' elif 'N' in status: status += ' Might be Affected' elif 'A' in status: status += ' Applied (injected)' if 'CVE' in desc: desc, cves = desc.rsplit(None, 1) cves = cves.split(',') else: cves = list() ret[glsa_id] = {'description': desc, 'status': status, 'CVEs': cves} except ValueError: pass return ret def glsa_check_list(glsa_list): ''' List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected' ''' cmd = 'glsa-check --quiet --nocolor --cve --list ' if isinstance(glsa_list, list): for glsa in glsa_list: cmd += glsa + ' ' elif glsa_list == 'all' or glsa_list == 'affected': cmd += glsa_list ret = dict() out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ret = _glsa_list_process_output(out) return ret
saltstack/salt
salt/modules/gentoolkitmod.py
_pretty_size
python
def _pretty_size(size): ''' Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1])
Print sizes in a similar fashion as eclean
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoolkitmod.py#L54-L62
null
# -*- coding: utf-8 -*- ''' Support for Gentoolkit ''' from __future__ import absolute_import, print_function, unicode_literals import os HAS_GENTOOLKIT = False # Import third party libs try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod HAS_GENTOOLKIT = True except ImportError: pass # Define the module's virtual name __virtualname__ = 'gentoolkit' def __virtual__(): ''' Only work on Gentoo systems with gentoolkit installed ''' if __grains__['os_family'] == 'Gentoo' and HAS_GENTOOLKIT: return __virtualname__ return (False, 'The gentoolkitmod execution module cannot be loaded: ' 'either the system is not Gentoo or the gentoolkit.eclean python module not available') def revdep_rebuild(lib=None): ''' Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild ''' cmd = 'revdep-rebuild -i --quiet --no-progress' if lib is not None: cmd += ' --library={0}'.format(lib) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def _parse_exclude(exclude_file): ''' Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile ''' if os.path.isfile(exclude_file): exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None) else: exclude = dict() return exclude def eclean_dist(destructive=False, package_names=False, size_limit=0, time_limit=0, fetch_restricted=False, exclude_file='/etc/eclean/distfiles.exclude'): ''' Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) if size_limit != 0: size_limit = cli.parseSize(size_limit) clean_size = 0 engine = search.DistfilesSearch(lambda x: None) clean_me, saved, deprecated = engine.findDistfiles( destructive=destructive, package_names=package_names, size_limit=size_limit, time_limit=time_limit, fetch_restricted=fetch_restricted, exclude=exclude) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_dist(clean_me) ret = {'cleaned': cleaned, 'saved': saved, 'deprecated': deprecated, 'total_cleaned': _pretty_size(clean_size)} return ret def eclean_pkg(destructive=False, package_names=False, time_limit=0, exclude_file='/etc/eclean/packages.exclude'): ''' Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) clean_size = 0 # findPackages requires one arg, but does nothing with it. # So we will just pass None in for the required arg clean_me = search.findPackages(None, destructive=destructive, package_names=package_names, time_limit=time_limit, exclude=exclude, pkgdir=search.pkgdir) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_pkgs(clean_me, search.pkgdir) ret = {'cleaned': cleaned, 'total_cleaned': _pretty_size(clean_size)} return ret def _glsa_list_process_output(output): ''' Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs ''' ret = dict() for line in output: try: glsa_id, status, desc = line.split(None, 2) if 'U' in status: status += ' Not Affected' elif 'N' in status: status += ' Might be Affected' elif 'A' in status: status += ' Applied (injected)' if 'CVE' in desc: desc, cves = desc.rsplit(None, 1) cves = cves.split(',') else: cves = list() ret[glsa_id] = {'description': desc, 'status': status, 'CVEs': cves} except ValueError: pass return ret def glsa_check_list(glsa_list): ''' List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected' ''' cmd = 'glsa-check --quiet --nocolor --cve --list ' if isinstance(glsa_list, list): for glsa in glsa_list: cmd += glsa + ' ' elif glsa_list == 'all' or glsa_list == 'affected': cmd += glsa_list ret = dict() out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ret = _glsa_list_process_output(out) return ret
saltstack/salt
salt/modules/gentoolkitmod.py
_parse_exclude
python
def _parse_exclude(exclude_file): ''' Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile ''' if os.path.isfile(exclude_file): exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None) else: exclude = dict() return exclude
Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoolkitmod.py#L65-L75
null
# -*- coding: utf-8 -*- ''' Support for Gentoolkit ''' from __future__ import absolute_import, print_function, unicode_literals import os HAS_GENTOOLKIT = False # Import third party libs try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod HAS_GENTOOLKIT = True except ImportError: pass # Define the module's virtual name __virtualname__ = 'gentoolkit' def __virtual__(): ''' Only work on Gentoo systems with gentoolkit installed ''' if __grains__['os_family'] == 'Gentoo' and HAS_GENTOOLKIT: return __virtualname__ return (False, 'The gentoolkitmod execution module cannot be loaded: ' 'either the system is not Gentoo or the gentoolkit.eclean python module not available') def revdep_rebuild(lib=None): ''' Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild ''' cmd = 'revdep-rebuild -i --quiet --no-progress' if lib is not None: cmd += ' --library={0}'.format(lib) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def _pretty_size(size): ''' Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1]) def eclean_dist(destructive=False, package_names=False, size_limit=0, time_limit=0, fetch_restricted=False, exclude_file='/etc/eclean/distfiles.exclude'): ''' Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) if size_limit != 0: size_limit = cli.parseSize(size_limit) clean_size = 0 engine = search.DistfilesSearch(lambda x: None) clean_me, saved, deprecated = engine.findDistfiles( destructive=destructive, package_names=package_names, size_limit=size_limit, time_limit=time_limit, fetch_restricted=fetch_restricted, exclude=exclude) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_dist(clean_me) ret = {'cleaned': cleaned, 'saved': saved, 'deprecated': deprecated, 'total_cleaned': _pretty_size(clean_size)} return ret def eclean_pkg(destructive=False, package_names=False, time_limit=0, exclude_file='/etc/eclean/packages.exclude'): ''' Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) clean_size = 0 # findPackages requires one arg, but does nothing with it. # So we will just pass None in for the required arg clean_me = search.findPackages(None, destructive=destructive, package_names=package_names, time_limit=time_limit, exclude=exclude, pkgdir=search.pkgdir) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_pkgs(clean_me, search.pkgdir) ret = {'cleaned': cleaned, 'total_cleaned': _pretty_size(clean_size)} return ret def _glsa_list_process_output(output): ''' Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs ''' ret = dict() for line in output: try: glsa_id, status, desc = line.split(None, 2) if 'U' in status: status += ' Not Affected' elif 'N' in status: status += ' Might be Affected' elif 'A' in status: status += ' Applied (injected)' if 'CVE' in desc: desc, cves = desc.rsplit(None, 1) cves = cves.split(',') else: cves = list() ret[glsa_id] = {'description': desc, 'status': status, 'CVEs': cves} except ValueError: pass return ret def glsa_check_list(glsa_list): ''' List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected' ''' cmd = 'glsa-check --quiet --nocolor --cve --list ' if isinstance(glsa_list, list): for glsa in glsa_list: cmd += glsa + ' ' elif glsa_list == 'all' or glsa_list == 'affected': cmd += glsa_list ret = dict() out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ret = _glsa_list_process_output(out) return ret
saltstack/salt
salt/modules/gentoolkitmod.py
eclean_dist
python
def eclean_dist(destructive=False, package_names=False, size_limit=0, time_limit=0, fetch_restricted=False, exclude_file='/etc/eclean/distfiles.exclude'): ''' Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) if size_limit != 0: size_limit = cli.parseSize(size_limit) clean_size = 0 engine = search.DistfilesSearch(lambda x: None) clean_me, saved, deprecated = engine.findDistfiles( destructive=destructive, package_names=package_names, size_limit=size_limit, time_limit=time_limit, fetch_restricted=fetch_restricted, exclude=exclude) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_dist(clean_me) ret = {'cleaned': cleaned, 'saved': saved, 'deprecated': deprecated, 'total_cleaned': _pretty_size(clean_size)} return ret
Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoolkitmod.py#L78-L159
[ "def _pretty_size(size):\n '''\n Print sizes in a similar fashion as eclean\n '''\n units = [' G', ' M', ' K', ' B']\n while units and size >= 1000:\n size = size / 1024.0\n units.pop()\n return '{0}{1}'.format(round(size, 1), units[-1])\n", "def _parse_exclude(exclude_file):\n '''\n Parse an exclude file.\n\n Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile\n '''\n if os.path.isfile(exclude_file):\n exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None)\n else:\n exclude = dict()\n return exclude\n" ]
# -*- coding: utf-8 -*- ''' Support for Gentoolkit ''' from __future__ import absolute_import, print_function, unicode_literals import os HAS_GENTOOLKIT = False # Import third party libs try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod HAS_GENTOOLKIT = True except ImportError: pass # Define the module's virtual name __virtualname__ = 'gentoolkit' def __virtual__(): ''' Only work on Gentoo systems with gentoolkit installed ''' if __grains__['os_family'] == 'Gentoo' and HAS_GENTOOLKIT: return __virtualname__ return (False, 'The gentoolkitmod execution module cannot be loaded: ' 'either the system is not Gentoo or the gentoolkit.eclean python module not available') def revdep_rebuild(lib=None): ''' Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild ''' cmd = 'revdep-rebuild -i --quiet --no-progress' if lib is not None: cmd += ' --library={0}'.format(lib) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def _pretty_size(size): ''' Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1]) def _parse_exclude(exclude_file): ''' Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile ''' if os.path.isfile(exclude_file): exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None) else: exclude = dict() return exclude def eclean_pkg(destructive=False, package_names=False, time_limit=0, exclude_file='/etc/eclean/packages.exclude'): ''' Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) clean_size = 0 # findPackages requires one arg, but does nothing with it. # So we will just pass None in for the required arg clean_me = search.findPackages(None, destructive=destructive, package_names=package_names, time_limit=time_limit, exclude=exclude, pkgdir=search.pkgdir) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_pkgs(clean_me, search.pkgdir) ret = {'cleaned': cleaned, 'total_cleaned': _pretty_size(clean_size)} return ret def _glsa_list_process_output(output): ''' Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs ''' ret = dict() for line in output: try: glsa_id, status, desc = line.split(None, 2) if 'U' in status: status += ' Not Affected' elif 'N' in status: status += ' Might be Affected' elif 'A' in status: status += ' Applied (injected)' if 'CVE' in desc: desc, cves = desc.rsplit(None, 1) cves = cves.split(',') else: cves = list() ret[glsa_id] = {'description': desc, 'status': status, 'CVEs': cves} except ValueError: pass return ret def glsa_check_list(glsa_list): ''' List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected' ''' cmd = 'glsa-check --quiet --nocolor --cve --list ' if isinstance(glsa_list, list): for glsa in glsa_list: cmd += glsa + ' ' elif glsa_list == 'all' or glsa_list == 'affected': cmd += glsa_list ret = dict() out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ret = _glsa_list_process_output(out) return ret
saltstack/salt
salt/modules/gentoolkitmod.py
eclean_pkg
python
def eclean_pkg(destructive=False, package_names=False, time_limit=0, exclude_file='/etc/eclean/packages.exclude'): ''' Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) clean_size = 0 # findPackages requires one arg, but does nothing with it. # So we will just pass None in for the required arg clean_me = search.findPackages(None, destructive=destructive, package_names=package_names, time_limit=time_limit, exclude=exclude, pkgdir=search.pkgdir) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_pkgs(clean_me, search.pkgdir) ret = {'cleaned': cleaned, 'total_cleaned': _pretty_size(clean_size)} return ret
Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoolkitmod.py#L162-L230
[ "def _pretty_size(size):\n '''\n Print sizes in a similar fashion as eclean\n '''\n units = [' G', ' M', ' K', ' B']\n while units and size >= 1000:\n size = size / 1024.0\n units.pop()\n return '{0}{1}'.format(round(size, 1), units[-1])\n", "def _parse_exclude(exclude_file):\n '''\n Parse an exclude file.\n\n Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile\n '''\n if os.path.isfile(exclude_file):\n exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None)\n else:\n exclude = dict()\n return exclude\n" ]
# -*- coding: utf-8 -*- ''' Support for Gentoolkit ''' from __future__ import absolute_import, print_function, unicode_literals import os HAS_GENTOOLKIT = False # Import third party libs try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod HAS_GENTOOLKIT = True except ImportError: pass # Define the module's virtual name __virtualname__ = 'gentoolkit' def __virtual__(): ''' Only work on Gentoo systems with gentoolkit installed ''' if __grains__['os_family'] == 'Gentoo' and HAS_GENTOOLKIT: return __virtualname__ return (False, 'The gentoolkitmod execution module cannot be loaded: ' 'either the system is not Gentoo or the gentoolkit.eclean python module not available') def revdep_rebuild(lib=None): ''' Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild ''' cmd = 'revdep-rebuild -i --quiet --no-progress' if lib is not None: cmd += ' --library={0}'.format(lib) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def _pretty_size(size): ''' Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1]) def _parse_exclude(exclude_file): ''' Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile ''' if os.path.isfile(exclude_file): exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None) else: exclude = dict() return exclude def eclean_dist(destructive=False, package_names=False, size_limit=0, time_limit=0, fetch_restricted=False, exclude_file='/etc/eclean/distfiles.exclude'): ''' Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) if size_limit != 0: size_limit = cli.parseSize(size_limit) clean_size = 0 engine = search.DistfilesSearch(lambda x: None) clean_me, saved, deprecated = engine.findDistfiles( destructive=destructive, package_names=package_names, size_limit=size_limit, time_limit=time_limit, fetch_restricted=fetch_restricted, exclude=exclude) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_dist(clean_me) ret = {'cleaned': cleaned, 'saved': saved, 'deprecated': deprecated, 'total_cleaned': _pretty_size(clean_size)} return ret def _glsa_list_process_output(output): ''' Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs ''' ret = dict() for line in output: try: glsa_id, status, desc = line.split(None, 2) if 'U' in status: status += ' Not Affected' elif 'N' in status: status += ' Might be Affected' elif 'A' in status: status += ' Applied (injected)' if 'CVE' in desc: desc, cves = desc.rsplit(None, 1) cves = cves.split(',') else: cves = list() ret[glsa_id] = {'description': desc, 'status': status, 'CVEs': cves} except ValueError: pass return ret def glsa_check_list(glsa_list): ''' List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected' ''' cmd = 'glsa-check --quiet --nocolor --cve --list ' if isinstance(glsa_list, list): for glsa in glsa_list: cmd += glsa + ' ' elif glsa_list == 'all' or glsa_list == 'affected': cmd += glsa_list ret = dict() out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ret = _glsa_list_process_output(out) return ret
saltstack/salt
salt/modules/gentoolkitmod.py
_glsa_list_process_output
python
def _glsa_list_process_output(output): ''' Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs ''' ret = dict() for line in output: try: glsa_id, status, desc = line.split(None, 2) if 'U' in status: status += ' Not Affected' elif 'N' in status: status += ' Might be Affected' elif 'A' in status: status += ' Applied (injected)' if 'CVE' in desc: desc, cves = desc.rsplit(None, 1) cves = cves.split(',') else: cves = list() ret[glsa_id] = {'description': desc, 'status': status, 'CVEs': cves} except ValueError: pass return ret
Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoolkitmod.py#L233-L258
null
# -*- coding: utf-8 -*- ''' Support for Gentoolkit ''' from __future__ import absolute_import, print_function, unicode_literals import os HAS_GENTOOLKIT = False # Import third party libs try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod HAS_GENTOOLKIT = True except ImportError: pass # Define the module's virtual name __virtualname__ = 'gentoolkit' def __virtual__(): ''' Only work on Gentoo systems with gentoolkit installed ''' if __grains__['os_family'] == 'Gentoo' and HAS_GENTOOLKIT: return __virtualname__ return (False, 'The gentoolkitmod execution module cannot be loaded: ' 'either the system is not Gentoo or the gentoolkit.eclean python module not available') def revdep_rebuild(lib=None): ''' Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild ''' cmd = 'revdep-rebuild -i --quiet --no-progress' if lib is not None: cmd += ' --library={0}'.format(lib) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def _pretty_size(size): ''' Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1]) def _parse_exclude(exclude_file): ''' Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile ''' if os.path.isfile(exclude_file): exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None) else: exclude = dict() return exclude def eclean_dist(destructive=False, package_names=False, size_limit=0, time_limit=0, fetch_restricted=False, exclude_file='/etc/eclean/distfiles.exclude'): ''' Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) if size_limit != 0: size_limit = cli.parseSize(size_limit) clean_size = 0 engine = search.DistfilesSearch(lambda x: None) clean_me, saved, deprecated = engine.findDistfiles( destructive=destructive, package_names=package_names, size_limit=size_limit, time_limit=time_limit, fetch_restricted=fetch_restricted, exclude=exclude) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_dist(clean_me) ret = {'cleaned': cleaned, 'saved': saved, 'deprecated': deprecated, 'total_cleaned': _pretty_size(clean_size)} return ret def eclean_pkg(destructive=False, package_names=False, time_limit=0, exclude_file='/etc/eclean/packages.exclude'): ''' Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) clean_size = 0 # findPackages requires one arg, but does nothing with it. # So we will just pass None in for the required arg clean_me = search.findPackages(None, destructive=destructive, package_names=package_names, time_limit=time_limit, exclude=exclude, pkgdir=search.pkgdir) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_pkgs(clean_me, search.pkgdir) ret = {'cleaned': cleaned, 'total_cleaned': _pretty_size(clean_size)} return ret def glsa_check_list(glsa_list): ''' List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected' ''' cmd = 'glsa-check --quiet --nocolor --cve --list ' if isinstance(glsa_list, list): for glsa in glsa_list: cmd += glsa + ' ' elif glsa_list == 'all' or glsa_list == 'affected': cmd += glsa_list ret = dict() out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ret = _glsa_list_process_output(out) return ret
saltstack/salt
salt/modules/gentoolkitmod.py
glsa_check_list
python
def glsa_check_list(glsa_list): ''' List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected' ''' cmd = 'glsa-check --quiet --nocolor --cve --list ' if isinstance(glsa_list, list): for glsa in glsa_list: cmd += glsa + ' ' elif glsa_list == 'all' or glsa_list == 'affected': cmd += glsa_list ret = dict() out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ret = _glsa_list_process_output(out) return ret
List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoolkitmod.py#L261-L293
[ "def _glsa_list_process_output(output):\n '''\n Process output from glsa_check_list into a dict\n\n Returns a dict containing the glsa id, description, status, and CVEs\n '''\n ret = dict()\n for line in output:\n try:\n glsa_id, status, desc = line.split(None, 2)\n if 'U' in status:\n status += ' Not Affected'\n elif 'N' in status:\n status += ' Might be Affected'\n elif 'A' in status:\n status += ' Applied (injected)'\n if 'CVE' in desc:\n desc, cves = desc.rsplit(None, 1)\n cves = cves.split(',')\n else:\n cves = list()\n ret[glsa_id] = {'description': desc, 'status': status,\n 'CVEs': cves}\n except ValueError:\n pass\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for Gentoolkit ''' from __future__ import absolute_import, print_function, unicode_literals import os HAS_GENTOOLKIT = False # Import third party libs try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod HAS_GENTOOLKIT = True except ImportError: pass # Define the module's virtual name __virtualname__ = 'gentoolkit' def __virtual__(): ''' Only work on Gentoo systems with gentoolkit installed ''' if __grains__['os_family'] == 'Gentoo' and HAS_GENTOOLKIT: return __virtualname__ return (False, 'The gentoolkitmod execution module cannot be loaded: ' 'either the system is not Gentoo or the gentoolkit.eclean python module not available') def revdep_rebuild(lib=None): ''' Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild ''' cmd = 'revdep-rebuild -i --quiet --no-progress' if lib is not None: cmd += ' --library={0}'.format(lib) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def _pretty_size(size): ''' Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1]) def _parse_exclude(exclude_file): ''' Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile ''' if os.path.isfile(exclude_file): exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None) else: exclude = dict() return exclude def eclean_dist(destructive=False, package_names=False, size_limit=0, time_limit=0, fetch_restricted=False, exclude_file='/etc/eclean/distfiles.exclude'): ''' Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) if size_limit != 0: size_limit = cli.parseSize(size_limit) clean_size = 0 engine = search.DistfilesSearch(lambda x: None) clean_me, saved, deprecated = engine.findDistfiles( destructive=destructive, package_names=package_names, size_limit=size_limit, time_limit=time_limit, fetch_restricted=fetch_restricted, exclude=exclude) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_dist(clean_me) ret = {'cleaned': cleaned, 'saved': saved, 'deprecated': deprecated, 'total_cleaned': _pretty_size(clean_size)} return ret def eclean_pkg(destructive=False, package_names=False, time_limit=0, exclude_file='/etc/eclean/packages.exclude'): ''' Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True ''' if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: 'Invalid exclusion file: {0}'.format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) clean_size = 0 # findPackages requires one arg, but does nothing with it. # So we will just pass None in for the required arg clean_me = search.findPackages(None, destructive=destructive, package_names=package_names, time_limit=time_limit, exclude=exclude, pkgdir=search.pkgdir) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_pkgs(clean_me, search.pkgdir) ret = {'cleaned': cleaned, 'total_cleaned': _pretty_size(clean_size)} return ret def _glsa_list_process_output(output): ''' Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs ''' ret = dict() for line in output: try: glsa_id, status, desc = line.split(None, 2) if 'U' in status: status += ' Not Affected' elif 'N' in status: status += ' Might be Affected' elif 'A' in status: status += ' Applied (injected)' if 'CVE' in desc: desc, cves = desc.rsplit(None, 1) cves = cves.split(',') else: cves = list() ret[glsa_id] = {'description': desc, 'status': status, 'CVEs': cves} except ValueError: pass return ret
saltstack/salt
salt/modules/monit.py
summary
python
def summary(svc_name=''): ''' Display a summary from monit CLI Example: .. code-block:: bash salt '*' monit.summary salt '*' monit.summary <service name> ''' ret = {} cmd = 'monit summary' res = __salt__['cmd.run'](cmd).splitlines() for line in res: if 'daemon is not running' in line: return dict(monit='daemon is not running', result=False) elif not line or svc_name not in line or 'The Monit daemon' in line: continue else: parts = line.split('\'') if len(parts) == 3: resource, name, status_ = ( parts[0].strip(), parts[1], parts[2].strip() ) if svc_name != '' and svc_name != name: continue if resource not in ret: ret[resource] = {} ret[resource][name] = status_ return ret
Display a summary from monit CLI Example: .. code-block:: bash salt '*' monit.summary salt '*' monit.summary <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/monit.py#L102-L132
null
# -*- coding: utf-8 -*- ''' Monit service module. This module will create a monit type service watcher. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re # Import salt libs import salt.utils.path # Function alias to make sure not to shadow built-in's __func_alias__ = { 'id_': 'id', 'reload_': 'reload', } def __virtual__(): if salt.utils.path.which('monit') is not None: # The monit binary exists, let the module load return True return (False, 'The monit execution module cannot be loaded: the monit binary is not in the path.') def start(name): ''' CLI Example: .. code-block:: bash salt '*' monit.start <service name> ''' cmd = 'monit start {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def stop(name): ''' Stops service via monit CLI Example: .. code-block:: bash salt '*' monit.stop <service name> ''' cmd = 'monit stop {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def restart(name): ''' Restart service via monit CLI Example: .. code-block:: bash salt '*' monit.restart <service name> ''' cmd = 'monit restart {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def unmonitor(name): ''' Unmonitor service via monit CLI Example: .. code-block:: bash salt '*' monit.unmonitor <service name> ''' cmd = 'monit unmonitor {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def monitor(name): ''' monitor service via monit CLI Example: .. code-block:: bash salt '*' monit.monitor <service name> ''' cmd = 'monit monitor {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def status(svc_name=''): ''' Display a process status from monit CLI Example: .. code-block:: bash salt '*' monit.status salt '*' monit.status <service name> ''' cmd = 'monit status' res = __salt__['cmd.run'](cmd) prostr = 'Process'+' '*28 s = res.replace('Process', prostr).replace("'", '').split('\n\n') entries = {} for process in s[1:-1]: pro = process.splitlines() tmp = {} for items in pro: key = items[:36].strip() tmp[key] = items[35:].strip() entries[pro[0].split()[1]] = tmp if svc_name == '': ret = entries else: ret = entries.get(svc_name, 'No such service') return ret def reload_(): ''' .. versionadded:: 2016.3.0 Reload monit configuration CLI Example: .. code-block:: bash salt '*' monit.reload ''' cmd = 'monit reload' return not __salt__['cmd.retcode'](cmd, python_shell=False) def configtest(): ''' .. versionadded:: 2016.3.0 Test monit configuration syntax CLI Example: .. code-block:: bash salt '*' monit.configtest ''' ret = {} cmd = 'monit -t' out = __salt__['cmd.run_all'](cmd) if out['retcode'] != 0: ret['comment'] = 'Syntax Error' ret['stderr'] = out['stderr'] ret['result'] = False return ret ret['comment'] = 'Syntax OK' ret['stdout'] = out['stdout'] ret['result'] = True return ret def version(): ''' .. versionadded:: 2016.3.0 Return version from monit -V CLI Example: .. code-block:: bash salt '*' monit.version ''' cmd = 'monit -V' out = __salt__['cmd.run'](cmd).splitlines() ret = out[0].split() return ret[-1] def id_(reset=False): ''' .. versionadded:: 2016.3.0 Return monit unique id. reset : False Reset current id and generate a new id when it's True. CLI Example: .. code-block:: bash salt '*' monit.id [reset=True] ''' if reset: id_pattern = re.compile(r'Monit id (?P<id>[^ ]+)') cmd = 'echo y|monit -r' out = __salt__['cmd.run_all'](cmd, python_shell=True) ret = id_pattern.search(out['stdout']).group('id') return ret if ret else False else: cmd = 'monit -i' out = __salt__['cmd.run'](cmd) ret = out.split(':')[-1].strip() return ret def validate(): ''' .. versionadded:: 2016.3.0 Check all services CLI Example: .. code-block:: bash salt '*' monit.validate ''' cmd = 'monit validate' return not __salt__['cmd.retcode'](cmd, python_shell=False)
saltstack/salt
salt/modules/monit.py
status
python
def status(svc_name=''): ''' Display a process status from monit CLI Example: .. code-block:: bash salt '*' monit.status salt '*' monit.status <service name> ''' cmd = 'monit status' res = __salt__['cmd.run'](cmd) prostr = 'Process'+' '*28 s = res.replace('Process', prostr).replace("'", '').split('\n\n') entries = {} for process in s[1:-1]: pro = process.splitlines() tmp = {} for items in pro: key = items[:36].strip() tmp[key] = items[35:].strip() entries[pro[0].split()[1]] = tmp if svc_name == '': ret = entries else: ret = entries.get(svc_name, 'No such service') return ret
Display a process status from monit CLI Example: .. code-block:: bash salt '*' monit.status salt '*' monit.status <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/monit.py#L135-L162
null
# -*- coding: utf-8 -*- ''' Monit service module. This module will create a monit type service watcher. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re # Import salt libs import salt.utils.path # Function alias to make sure not to shadow built-in's __func_alias__ = { 'id_': 'id', 'reload_': 'reload', } def __virtual__(): if salt.utils.path.which('monit') is not None: # The monit binary exists, let the module load return True return (False, 'The monit execution module cannot be loaded: the monit binary is not in the path.') def start(name): ''' CLI Example: .. code-block:: bash salt '*' monit.start <service name> ''' cmd = 'monit start {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def stop(name): ''' Stops service via monit CLI Example: .. code-block:: bash salt '*' monit.stop <service name> ''' cmd = 'monit stop {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def restart(name): ''' Restart service via monit CLI Example: .. code-block:: bash salt '*' monit.restart <service name> ''' cmd = 'monit restart {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def unmonitor(name): ''' Unmonitor service via monit CLI Example: .. code-block:: bash salt '*' monit.unmonitor <service name> ''' cmd = 'monit unmonitor {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def monitor(name): ''' monitor service via monit CLI Example: .. code-block:: bash salt '*' monit.monitor <service name> ''' cmd = 'monit monitor {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def summary(svc_name=''): ''' Display a summary from monit CLI Example: .. code-block:: bash salt '*' monit.summary salt '*' monit.summary <service name> ''' ret = {} cmd = 'monit summary' res = __salt__['cmd.run'](cmd).splitlines() for line in res: if 'daemon is not running' in line: return dict(monit='daemon is not running', result=False) elif not line or svc_name not in line or 'The Monit daemon' in line: continue else: parts = line.split('\'') if len(parts) == 3: resource, name, status_ = ( parts[0].strip(), parts[1], parts[2].strip() ) if svc_name != '' and svc_name != name: continue if resource not in ret: ret[resource] = {} ret[resource][name] = status_ return ret def reload_(): ''' .. versionadded:: 2016.3.0 Reload monit configuration CLI Example: .. code-block:: bash salt '*' monit.reload ''' cmd = 'monit reload' return not __salt__['cmd.retcode'](cmd, python_shell=False) def configtest(): ''' .. versionadded:: 2016.3.0 Test monit configuration syntax CLI Example: .. code-block:: bash salt '*' monit.configtest ''' ret = {} cmd = 'monit -t' out = __salt__['cmd.run_all'](cmd) if out['retcode'] != 0: ret['comment'] = 'Syntax Error' ret['stderr'] = out['stderr'] ret['result'] = False return ret ret['comment'] = 'Syntax OK' ret['stdout'] = out['stdout'] ret['result'] = True return ret def version(): ''' .. versionadded:: 2016.3.0 Return version from monit -V CLI Example: .. code-block:: bash salt '*' monit.version ''' cmd = 'monit -V' out = __salt__['cmd.run'](cmd).splitlines() ret = out[0].split() return ret[-1] def id_(reset=False): ''' .. versionadded:: 2016.3.0 Return monit unique id. reset : False Reset current id and generate a new id when it's True. CLI Example: .. code-block:: bash salt '*' monit.id [reset=True] ''' if reset: id_pattern = re.compile(r'Monit id (?P<id>[^ ]+)') cmd = 'echo y|monit -r' out = __salt__['cmd.run_all'](cmd, python_shell=True) ret = id_pattern.search(out['stdout']).group('id') return ret if ret else False else: cmd = 'monit -i' out = __salt__['cmd.run'](cmd) ret = out.split(':')[-1].strip() return ret def validate(): ''' .. versionadded:: 2016.3.0 Check all services CLI Example: .. code-block:: bash salt '*' monit.validate ''' cmd = 'monit validate' return not __salt__['cmd.retcode'](cmd, python_shell=False)
saltstack/salt
salt/modules/monit.py
id_
python
def id_(reset=False): ''' .. versionadded:: 2016.3.0 Return monit unique id. reset : False Reset current id and generate a new id when it's True. CLI Example: .. code-block:: bash salt '*' monit.id [reset=True] ''' if reset: id_pattern = re.compile(r'Monit id (?P<id>[^ ]+)') cmd = 'echo y|monit -r' out = __salt__['cmd.run_all'](cmd, python_shell=True) ret = id_pattern.search(out['stdout']).group('id') return ret if ret else False else: cmd = 'monit -i' out = __salt__['cmd.run'](cmd) ret = out.split(':')[-1].strip() return ret
.. versionadded:: 2016.3.0 Return monit unique id. reset : False Reset current id and generate a new id when it's True. CLI Example: .. code-block:: bash salt '*' monit.id [reset=True]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/monit.py#L227-L252
null
# -*- coding: utf-8 -*- ''' Monit service module. This module will create a monit type service watcher. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re # Import salt libs import salt.utils.path # Function alias to make sure not to shadow built-in's __func_alias__ = { 'id_': 'id', 'reload_': 'reload', } def __virtual__(): if salt.utils.path.which('monit') is not None: # The monit binary exists, let the module load return True return (False, 'The monit execution module cannot be loaded: the monit binary is not in the path.') def start(name): ''' CLI Example: .. code-block:: bash salt '*' monit.start <service name> ''' cmd = 'monit start {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def stop(name): ''' Stops service via monit CLI Example: .. code-block:: bash salt '*' monit.stop <service name> ''' cmd = 'monit stop {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def restart(name): ''' Restart service via monit CLI Example: .. code-block:: bash salt '*' monit.restart <service name> ''' cmd = 'monit restart {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def unmonitor(name): ''' Unmonitor service via monit CLI Example: .. code-block:: bash salt '*' monit.unmonitor <service name> ''' cmd = 'monit unmonitor {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def monitor(name): ''' monitor service via monit CLI Example: .. code-block:: bash salt '*' monit.monitor <service name> ''' cmd = 'monit monitor {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False) def summary(svc_name=''): ''' Display a summary from monit CLI Example: .. code-block:: bash salt '*' monit.summary salt '*' monit.summary <service name> ''' ret = {} cmd = 'monit summary' res = __salt__['cmd.run'](cmd).splitlines() for line in res: if 'daemon is not running' in line: return dict(monit='daemon is not running', result=False) elif not line or svc_name not in line or 'The Monit daemon' in line: continue else: parts = line.split('\'') if len(parts) == 3: resource, name, status_ = ( parts[0].strip(), parts[1], parts[2].strip() ) if svc_name != '' and svc_name != name: continue if resource not in ret: ret[resource] = {} ret[resource][name] = status_ return ret def status(svc_name=''): ''' Display a process status from monit CLI Example: .. code-block:: bash salt '*' monit.status salt '*' monit.status <service name> ''' cmd = 'monit status' res = __salt__['cmd.run'](cmd) prostr = 'Process'+' '*28 s = res.replace('Process', prostr).replace("'", '').split('\n\n') entries = {} for process in s[1:-1]: pro = process.splitlines() tmp = {} for items in pro: key = items[:36].strip() tmp[key] = items[35:].strip() entries[pro[0].split()[1]] = tmp if svc_name == '': ret = entries else: ret = entries.get(svc_name, 'No such service') return ret def reload_(): ''' .. versionadded:: 2016.3.0 Reload monit configuration CLI Example: .. code-block:: bash salt '*' monit.reload ''' cmd = 'monit reload' return not __salt__['cmd.retcode'](cmd, python_shell=False) def configtest(): ''' .. versionadded:: 2016.3.0 Test monit configuration syntax CLI Example: .. code-block:: bash salt '*' monit.configtest ''' ret = {} cmd = 'monit -t' out = __salt__['cmd.run_all'](cmd) if out['retcode'] != 0: ret['comment'] = 'Syntax Error' ret['stderr'] = out['stderr'] ret['result'] = False return ret ret['comment'] = 'Syntax OK' ret['stdout'] = out['stdout'] ret['result'] = True return ret def version(): ''' .. versionadded:: 2016.3.0 Return version from monit -V CLI Example: .. code-block:: bash salt '*' monit.version ''' cmd = 'monit -V' out = __salt__['cmd.run'](cmd).splitlines() ret = out[0].split() return ret[-1] def validate(): ''' .. versionadded:: 2016.3.0 Check all services CLI Example: .. code-block:: bash salt '*' monit.validate ''' cmd = 'monit validate' return not __salt__['cmd.retcode'](cmd, python_shell=False)
saltstack/salt
salt/utils/state.py
search_onfail_requisites
python
def search_onfail_requisites(sid, highstate): ''' For a particular low chunk, search relevant onfail related states ''' onfails = [] if '_|-' in sid: st = salt.state.split_low_tag(sid) else: st = {'__id__': sid} for fstate, fchunks in six.iteritems(highstate): if fstate == st['__id__']: continue else: for mod_, fchunk in six.iteritems(fchunks): if ( not isinstance(mod_, six.string_types) or mod_.startswith('__') ): continue else: if not isinstance(fchunk, list): continue else: # bydefault onfail will fail, but you can # set onfail_stop: False to prevent the highstate # to stop if you handle it onfail_handled = False for fdata in fchunk: if not isinstance(fdata, dict): continue onfail_handled = (fdata.get('onfail_stop', True) is False) if onfail_handled: break if not onfail_handled: continue for fdata in fchunk: if not isinstance(fdata, dict): continue for knob, fvalue in six.iteritems(fdata): if knob != 'onfail': continue for freqs in fvalue: for fmod, fid in six.iteritems(freqs): if not ( fid == st['__id__'] and fmod == st.get('state', fmod) ): continue onfails.append((fstate, mod_, fchunk)) return onfails
For a particular low chunk, search relevant onfail related states
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/state.py#L27-L77
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def split_low_tag(tag):\n '''\n Take a low tag and split it back into the low dict that it came from\n '''\n state, id_, name, fun = tag.split('_|-')\n\n return {'state': state,\n '__id__': id_,\n 'name': name,\n 'fun': fun}\n" ]
# -*- coding: utf-8 -*- ''' Utility functions for state functions .. versionadded:: 2018.3.0 ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import copy # Import Salt libs from salt.ext import six from salt.exceptions import CommandExecutionError import salt.state _empty = object() def gen_tag(low): ''' Generate the running dict tag string from the low data structure ''' return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low) def check_onfail_requisites(state_id, state_result, running, highstate): ''' When a state fail and is part of a highstate, check if there is onfail requisites. When we find onfail requisites, we will consider the state failed only if at least one of those onfail requisites also failed Returns: True: if onfail handlers suceeded False: if one on those handler failed None: if the state does not have onfail requisites ''' nret = None if ( state_id and state_result and highstate and isinstance(highstate, dict) ): onfails = search_onfail_requisites(state_id, highstate) if onfails: for handler in onfails: fstate, mod_, fchunk = handler for rstateid, rstate in six.iteritems(running): if '_|-' in rstateid: st = salt.state.split_low_tag(rstateid) # in case of simple state, try to guess else: id_ = rstate.get('__id__', rstateid) if not id_: raise ValueError('no state id') st = {'__id__': id_, 'state': mod_} if mod_ == st['state'] and fstate == st['__id__']: ofresult = rstate.get('result', _empty) if ofresult in [False, True]: nret = ofresult if ofresult is False: # as soon as we find an errored onfail, we stop break # consider that if we parsed onfailes without changing # the ret, that we have failed if nret is None: nret = False return nret def check_result(running, recurse=False, highstate=None): ''' Check the total return value of the run and determine if the running dict has any issues ''' if not isinstance(running, dict): return False if not running: return False ret = True for state_id, state_result in six.iteritems(running): expected_type = dict # The __extend__ state is a list if "__extend__" == state_id: expected_type = list if not recurse and not isinstance(state_result, expected_type): ret = False if ret and isinstance(state_result, dict): result = state_result.get('result', _empty) if result is False: ret = False # only override return value if we are not already failed elif result is _empty and isinstance(state_result, dict) and ret: ret = check_result( state_result, recurse=True, highstate=highstate) # if we detect a fail, check for onfail requisites if not ret: # ret can be None in case of no onfail reqs, recast it to bool ret = bool(check_onfail_requisites(state_id, state_result, running, highstate)) # return as soon as we got a failure if not ret: break return ret def merge_subreturn(original_return, sub_return, subkey=None): ''' Update an existing state return (`original_return`) in place with another state return (`sub_return`), i.e. for a subresource. Returns: dict: The updated state return. The existing state return does not need to have all the required fields, as this is meant to be called from the internals of a state function, but any existing data will be kept and respected. It is important after using this function to check the return value to see if it is False, in which case the main state should return. Prefer to check `_ret['result']` instead of `ret['result']`, as the latter field may not yet be populated. Code Example: .. code-block:: python def state_func(name, config, alarm=None): ret = {'name': name, 'comment': '', 'changes': {}} if alarm: _ret = __states__['subresource.managed'](alarm) __utils__['state.merge_subreturn'](ret, _ret) if _ret['result'] is False: return ret ''' if not subkey: subkey = sub_return['name'] if sub_return['result'] is False: # True or None stay the same original_return['result'] = sub_return['result'] sub_comment = sub_return['comment'] if not isinstance(sub_comment, list): sub_comment = [sub_comment] original_return.setdefault('comment', []) if isinstance(original_return['comment'], list): original_return['comment'].extend(sub_comment) else: if original_return['comment']: # Skip for empty original comments original_return['comment'] += '\n' original_return['comment'] += '\n'.join(sub_comment) if sub_return['changes']: # changes always exists original_return.setdefault('changes', {}) original_return['changes'][subkey] = sub_return['changes'] return original_return def get_sls_opts(opts, **kwargs): ''' Return a copy of the opts for use, optionally load a local config on top ''' opts = copy.deepcopy(opts) if 'localconfig' in kwargs: return salt.config.minion_config(kwargs['localconfig'], defaults=opts) if 'saltenv' in kwargs: saltenv = kwargs['saltenv'] if saltenv is not None: if not isinstance(saltenv, six.string_types): saltenv = six.text_type(saltenv) if opts['lock_saltenv'] and saltenv != opts['saltenv']: raise CommandExecutionError( 'lock_saltenv is enabled, saltenv cannot be changed' ) opts['saltenv'] = kwargs['saltenv'] pillarenv = None if kwargs.get('pillarenv'): pillarenv = kwargs.get('pillarenv') if opts.get('pillarenv_from_saltenv') and not pillarenv: pillarenv = kwargs.get('saltenv') if pillarenv is not None and not isinstance(pillarenv, six.string_types): opts['pillarenv'] = six.text_type(pillarenv) else: opts['pillarenv'] = pillarenv return opts
saltstack/salt
salt/utils/state.py
check_onfail_requisites
python
def check_onfail_requisites(state_id, state_result, running, highstate): ''' When a state fail and is part of a highstate, check if there is onfail requisites. When we find onfail requisites, we will consider the state failed only if at least one of those onfail requisites also failed Returns: True: if onfail handlers suceeded False: if one on those handler failed None: if the state does not have onfail requisites ''' nret = None if ( state_id and state_result and highstate and isinstance(highstate, dict) ): onfails = search_onfail_requisites(state_id, highstate) if onfails: for handler in onfails: fstate, mod_, fchunk = handler for rstateid, rstate in six.iteritems(running): if '_|-' in rstateid: st = salt.state.split_low_tag(rstateid) # in case of simple state, try to guess else: id_ = rstate.get('__id__', rstateid) if not id_: raise ValueError('no state id') st = {'__id__': id_, 'state': mod_} if mod_ == st['state'] and fstate == st['__id__']: ofresult = rstate.get('result', _empty) if ofresult in [False, True]: nret = ofresult if ofresult is False: # as soon as we find an errored onfail, we stop break # consider that if we parsed onfailes without changing # the ret, that we have failed if nret is None: nret = False return nret
When a state fail and is part of a highstate, check if there is onfail requisites. When we find onfail requisites, we will consider the state failed only if at least one of those onfail requisites also failed Returns: True: if onfail handlers suceeded False: if one on those handler failed None: if the state does not have onfail requisites
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/state.py#L80-L123
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def split_low_tag(tag):\n '''\n Take a low tag and split it back into the low dict that it came from\n '''\n state, id_, name, fun = tag.split('_|-')\n\n return {'state': state,\n '__id__': id_,\n 'name': name,\n 'fun': fun}\n", "def search_onfail_requisites(sid, highstate):\n '''\n For a particular low chunk, search relevant onfail related states\n '''\n onfails = []\n if '_|-' in sid:\n st = salt.state.split_low_tag(sid)\n else:\n st = {'__id__': sid}\n for fstate, fchunks in six.iteritems(highstate):\n if fstate == st['__id__']:\n continue\n else:\n for mod_, fchunk in six.iteritems(fchunks):\n if (\n not isinstance(mod_, six.string_types) or\n mod_.startswith('__')\n ):\n continue\n else:\n if not isinstance(fchunk, list):\n continue\n else:\n # bydefault onfail will fail, but you can\n # set onfail_stop: False to prevent the highstate\n # to stop if you handle it\n onfail_handled = False\n for fdata in fchunk:\n if not isinstance(fdata, dict):\n continue\n onfail_handled = (fdata.get('onfail_stop', True)\n is False)\n if onfail_handled:\n break\n if not onfail_handled:\n continue\n for fdata in fchunk:\n if not isinstance(fdata, dict):\n continue\n for knob, fvalue in six.iteritems(fdata):\n if knob != 'onfail':\n continue\n for freqs in fvalue:\n for fmod, fid in six.iteritems(freqs):\n if not (\n fid == st['__id__'] and\n fmod == st.get('state', fmod)\n ):\n continue\n onfails.append((fstate, mod_, fchunk))\n return onfails\n" ]
# -*- coding: utf-8 -*- ''' Utility functions for state functions .. versionadded:: 2018.3.0 ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import copy # Import Salt libs from salt.ext import six from salt.exceptions import CommandExecutionError import salt.state _empty = object() def gen_tag(low): ''' Generate the running dict tag string from the low data structure ''' return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low) def search_onfail_requisites(sid, highstate): ''' For a particular low chunk, search relevant onfail related states ''' onfails = [] if '_|-' in sid: st = salt.state.split_low_tag(sid) else: st = {'__id__': sid} for fstate, fchunks in six.iteritems(highstate): if fstate == st['__id__']: continue else: for mod_, fchunk in six.iteritems(fchunks): if ( not isinstance(mod_, six.string_types) or mod_.startswith('__') ): continue else: if not isinstance(fchunk, list): continue else: # bydefault onfail will fail, but you can # set onfail_stop: False to prevent the highstate # to stop if you handle it onfail_handled = False for fdata in fchunk: if not isinstance(fdata, dict): continue onfail_handled = (fdata.get('onfail_stop', True) is False) if onfail_handled: break if not onfail_handled: continue for fdata in fchunk: if not isinstance(fdata, dict): continue for knob, fvalue in six.iteritems(fdata): if knob != 'onfail': continue for freqs in fvalue: for fmod, fid in six.iteritems(freqs): if not ( fid == st['__id__'] and fmod == st.get('state', fmod) ): continue onfails.append((fstate, mod_, fchunk)) return onfails def check_result(running, recurse=False, highstate=None): ''' Check the total return value of the run and determine if the running dict has any issues ''' if not isinstance(running, dict): return False if not running: return False ret = True for state_id, state_result in six.iteritems(running): expected_type = dict # The __extend__ state is a list if "__extend__" == state_id: expected_type = list if not recurse and not isinstance(state_result, expected_type): ret = False if ret and isinstance(state_result, dict): result = state_result.get('result', _empty) if result is False: ret = False # only override return value if we are not already failed elif result is _empty and isinstance(state_result, dict) and ret: ret = check_result( state_result, recurse=True, highstate=highstate) # if we detect a fail, check for onfail requisites if not ret: # ret can be None in case of no onfail reqs, recast it to bool ret = bool(check_onfail_requisites(state_id, state_result, running, highstate)) # return as soon as we got a failure if not ret: break return ret def merge_subreturn(original_return, sub_return, subkey=None): ''' Update an existing state return (`original_return`) in place with another state return (`sub_return`), i.e. for a subresource. Returns: dict: The updated state return. The existing state return does not need to have all the required fields, as this is meant to be called from the internals of a state function, but any existing data will be kept and respected. It is important after using this function to check the return value to see if it is False, in which case the main state should return. Prefer to check `_ret['result']` instead of `ret['result']`, as the latter field may not yet be populated. Code Example: .. code-block:: python def state_func(name, config, alarm=None): ret = {'name': name, 'comment': '', 'changes': {}} if alarm: _ret = __states__['subresource.managed'](alarm) __utils__['state.merge_subreturn'](ret, _ret) if _ret['result'] is False: return ret ''' if not subkey: subkey = sub_return['name'] if sub_return['result'] is False: # True or None stay the same original_return['result'] = sub_return['result'] sub_comment = sub_return['comment'] if not isinstance(sub_comment, list): sub_comment = [sub_comment] original_return.setdefault('comment', []) if isinstance(original_return['comment'], list): original_return['comment'].extend(sub_comment) else: if original_return['comment']: # Skip for empty original comments original_return['comment'] += '\n' original_return['comment'] += '\n'.join(sub_comment) if sub_return['changes']: # changes always exists original_return.setdefault('changes', {}) original_return['changes'][subkey] = sub_return['changes'] return original_return def get_sls_opts(opts, **kwargs): ''' Return a copy of the opts for use, optionally load a local config on top ''' opts = copy.deepcopy(opts) if 'localconfig' in kwargs: return salt.config.minion_config(kwargs['localconfig'], defaults=opts) if 'saltenv' in kwargs: saltenv = kwargs['saltenv'] if saltenv is not None: if not isinstance(saltenv, six.string_types): saltenv = six.text_type(saltenv) if opts['lock_saltenv'] and saltenv != opts['saltenv']: raise CommandExecutionError( 'lock_saltenv is enabled, saltenv cannot be changed' ) opts['saltenv'] = kwargs['saltenv'] pillarenv = None if kwargs.get('pillarenv'): pillarenv = kwargs.get('pillarenv') if opts.get('pillarenv_from_saltenv') and not pillarenv: pillarenv = kwargs.get('saltenv') if pillarenv is not None and not isinstance(pillarenv, six.string_types): opts['pillarenv'] = six.text_type(pillarenv) else: opts['pillarenv'] = pillarenv return opts
saltstack/salt
salt/utils/state.py
check_result
python
def check_result(running, recurse=False, highstate=None): ''' Check the total return value of the run and determine if the running dict has any issues ''' if not isinstance(running, dict): return False if not running: return False ret = True for state_id, state_result in six.iteritems(running): expected_type = dict # The __extend__ state is a list if "__extend__" == state_id: expected_type = list if not recurse and not isinstance(state_result, expected_type): ret = False if ret and isinstance(state_result, dict): result = state_result.get('result', _empty) if result is False: ret = False # only override return value if we are not already failed elif result is _empty and isinstance(state_result, dict) and ret: ret = check_result( state_result, recurse=True, highstate=highstate) # if we detect a fail, check for onfail requisites if not ret: # ret can be None in case of no onfail reqs, recast it to bool ret = bool(check_onfail_requisites(state_id, state_result, running, highstate)) # return as soon as we got a failure if not ret: break return ret
Check the total return value of the run and determine if the running dict has any issues
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/state.py#L126-L161
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def check_result(running, recurse=False, highstate=None):\n '''\n Check the total return value of the run and determine if the running\n dict has any issues\n '''\n if not isinstance(running, dict):\n return False\n\n if not running:\n return False\n\n ret = True\n for state_id, state_result in six.iteritems(running):\n expected_type = dict\n # The __extend__ state is a list\n if \"__extend__\" == state_id:\n expected_type = list\n if not recurse and not isinstance(state_result, expected_type):\n ret = False\n if ret and isinstance(state_result, dict):\n result = state_result.get('result', _empty)\n if result is False:\n ret = False\n # only override return value if we are not already failed\n elif result is _empty and isinstance(state_result, dict) and ret:\n ret = check_result(\n state_result, recurse=True, highstate=highstate)\n # if we detect a fail, check for onfail requisites\n if not ret:\n # ret can be None in case of no onfail reqs, recast it to bool\n ret = bool(check_onfail_requisites(state_id, state_result,\n running, highstate))\n # return as soon as we got a failure\n if not ret:\n break\n return ret\n", "def check_onfail_requisites(state_id, state_result, running, highstate):\n '''\n When a state fail and is part of a highstate, check\n if there is onfail requisites.\n When we find onfail requisites, we will consider the state failed\n only if at least one of those onfail requisites also failed\n\n Returns:\n\n True: if onfail handlers suceeded\n False: if one on those handler failed\n None: if the state does not have onfail requisites\n\n '''\n nret = None\n if (\n state_id and state_result and\n highstate and isinstance(highstate, dict)\n ):\n onfails = search_onfail_requisites(state_id, highstate)\n if onfails:\n for handler in onfails:\n fstate, mod_, fchunk = handler\n for rstateid, rstate in six.iteritems(running):\n if '_|-' in rstateid:\n st = salt.state.split_low_tag(rstateid)\n # in case of simple state, try to guess\n else:\n id_ = rstate.get('__id__', rstateid)\n if not id_:\n raise ValueError('no state id')\n st = {'__id__': id_, 'state': mod_}\n if mod_ == st['state'] and fstate == st['__id__']:\n ofresult = rstate.get('result', _empty)\n if ofresult in [False, True]:\n nret = ofresult\n if ofresult is False:\n # as soon as we find an errored onfail, we stop\n break\n # consider that if we parsed onfailes without changing\n # the ret, that we have failed\n if nret is None:\n nret = False\n return nret\n" ]
# -*- coding: utf-8 -*- ''' Utility functions for state functions .. versionadded:: 2018.3.0 ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import copy # Import Salt libs from salt.ext import six from salt.exceptions import CommandExecutionError import salt.state _empty = object() def gen_tag(low): ''' Generate the running dict tag string from the low data structure ''' return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low) def search_onfail_requisites(sid, highstate): ''' For a particular low chunk, search relevant onfail related states ''' onfails = [] if '_|-' in sid: st = salt.state.split_low_tag(sid) else: st = {'__id__': sid} for fstate, fchunks in six.iteritems(highstate): if fstate == st['__id__']: continue else: for mod_, fchunk in six.iteritems(fchunks): if ( not isinstance(mod_, six.string_types) or mod_.startswith('__') ): continue else: if not isinstance(fchunk, list): continue else: # bydefault onfail will fail, but you can # set onfail_stop: False to prevent the highstate # to stop if you handle it onfail_handled = False for fdata in fchunk: if not isinstance(fdata, dict): continue onfail_handled = (fdata.get('onfail_stop', True) is False) if onfail_handled: break if not onfail_handled: continue for fdata in fchunk: if not isinstance(fdata, dict): continue for knob, fvalue in six.iteritems(fdata): if knob != 'onfail': continue for freqs in fvalue: for fmod, fid in six.iteritems(freqs): if not ( fid == st['__id__'] and fmod == st.get('state', fmod) ): continue onfails.append((fstate, mod_, fchunk)) return onfails def check_onfail_requisites(state_id, state_result, running, highstate): ''' When a state fail and is part of a highstate, check if there is onfail requisites. When we find onfail requisites, we will consider the state failed only if at least one of those onfail requisites also failed Returns: True: if onfail handlers suceeded False: if one on those handler failed None: if the state does not have onfail requisites ''' nret = None if ( state_id and state_result and highstate and isinstance(highstate, dict) ): onfails = search_onfail_requisites(state_id, highstate) if onfails: for handler in onfails: fstate, mod_, fchunk = handler for rstateid, rstate in six.iteritems(running): if '_|-' in rstateid: st = salt.state.split_low_tag(rstateid) # in case of simple state, try to guess else: id_ = rstate.get('__id__', rstateid) if not id_: raise ValueError('no state id') st = {'__id__': id_, 'state': mod_} if mod_ == st['state'] and fstate == st['__id__']: ofresult = rstate.get('result', _empty) if ofresult in [False, True]: nret = ofresult if ofresult is False: # as soon as we find an errored onfail, we stop break # consider that if we parsed onfailes without changing # the ret, that we have failed if nret is None: nret = False return nret def merge_subreturn(original_return, sub_return, subkey=None): ''' Update an existing state return (`original_return`) in place with another state return (`sub_return`), i.e. for a subresource. Returns: dict: The updated state return. The existing state return does not need to have all the required fields, as this is meant to be called from the internals of a state function, but any existing data will be kept and respected. It is important after using this function to check the return value to see if it is False, in which case the main state should return. Prefer to check `_ret['result']` instead of `ret['result']`, as the latter field may not yet be populated. Code Example: .. code-block:: python def state_func(name, config, alarm=None): ret = {'name': name, 'comment': '', 'changes': {}} if alarm: _ret = __states__['subresource.managed'](alarm) __utils__['state.merge_subreturn'](ret, _ret) if _ret['result'] is False: return ret ''' if not subkey: subkey = sub_return['name'] if sub_return['result'] is False: # True or None stay the same original_return['result'] = sub_return['result'] sub_comment = sub_return['comment'] if not isinstance(sub_comment, list): sub_comment = [sub_comment] original_return.setdefault('comment', []) if isinstance(original_return['comment'], list): original_return['comment'].extend(sub_comment) else: if original_return['comment']: # Skip for empty original comments original_return['comment'] += '\n' original_return['comment'] += '\n'.join(sub_comment) if sub_return['changes']: # changes always exists original_return.setdefault('changes', {}) original_return['changes'][subkey] = sub_return['changes'] return original_return def get_sls_opts(opts, **kwargs): ''' Return a copy of the opts for use, optionally load a local config on top ''' opts = copy.deepcopy(opts) if 'localconfig' in kwargs: return salt.config.minion_config(kwargs['localconfig'], defaults=opts) if 'saltenv' in kwargs: saltenv = kwargs['saltenv'] if saltenv is not None: if not isinstance(saltenv, six.string_types): saltenv = six.text_type(saltenv) if opts['lock_saltenv'] and saltenv != opts['saltenv']: raise CommandExecutionError( 'lock_saltenv is enabled, saltenv cannot be changed' ) opts['saltenv'] = kwargs['saltenv'] pillarenv = None if kwargs.get('pillarenv'): pillarenv = kwargs.get('pillarenv') if opts.get('pillarenv_from_saltenv') and not pillarenv: pillarenv = kwargs.get('saltenv') if pillarenv is not None and not isinstance(pillarenv, six.string_types): opts['pillarenv'] = six.text_type(pillarenv) else: opts['pillarenv'] = pillarenv return opts
saltstack/salt
salt/utils/state.py
merge_subreturn
python
def merge_subreturn(original_return, sub_return, subkey=None): ''' Update an existing state return (`original_return`) in place with another state return (`sub_return`), i.e. for a subresource. Returns: dict: The updated state return. The existing state return does not need to have all the required fields, as this is meant to be called from the internals of a state function, but any existing data will be kept and respected. It is important after using this function to check the return value to see if it is False, in which case the main state should return. Prefer to check `_ret['result']` instead of `ret['result']`, as the latter field may not yet be populated. Code Example: .. code-block:: python def state_func(name, config, alarm=None): ret = {'name': name, 'comment': '', 'changes': {}} if alarm: _ret = __states__['subresource.managed'](alarm) __utils__['state.merge_subreturn'](ret, _ret) if _ret['result'] is False: return ret ''' if not subkey: subkey = sub_return['name'] if sub_return['result'] is False: # True or None stay the same original_return['result'] = sub_return['result'] sub_comment = sub_return['comment'] if not isinstance(sub_comment, list): sub_comment = [sub_comment] original_return.setdefault('comment', []) if isinstance(original_return['comment'], list): original_return['comment'].extend(sub_comment) else: if original_return['comment']: # Skip for empty original comments original_return['comment'] += '\n' original_return['comment'] += '\n'.join(sub_comment) if sub_return['changes']: # changes always exists original_return.setdefault('changes', {}) original_return['changes'][subkey] = sub_return['changes'] return original_return
Update an existing state return (`original_return`) in place with another state return (`sub_return`), i.e. for a subresource. Returns: dict: The updated state return. The existing state return does not need to have all the required fields, as this is meant to be called from the internals of a state function, but any existing data will be kept and respected. It is important after using this function to check the return value to see if it is False, in which case the main state should return. Prefer to check `_ret['result']` instead of `ret['result']`, as the latter field may not yet be populated. Code Example: .. code-block:: python def state_func(name, config, alarm=None): ret = {'name': name, 'comment': '', 'changes': {}} if alarm: _ret = __states__['subresource.managed'](alarm) __utils__['state.merge_subreturn'](ret, _ret) if _ret['result'] is False: return ret
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/state.py#L164-L215
null
# -*- coding: utf-8 -*- ''' Utility functions for state functions .. versionadded:: 2018.3.0 ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import copy # Import Salt libs from salt.ext import six from salt.exceptions import CommandExecutionError import salt.state _empty = object() def gen_tag(low): ''' Generate the running dict tag string from the low data structure ''' return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low) def search_onfail_requisites(sid, highstate): ''' For a particular low chunk, search relevant onfail related states ''' onfails = [] if '_|-' in sid: st = salt.state.split_low_tag(sid) else: st = {'__id__': sid} for fstate, fchunks in six.iteritems(highstate): if fstate == st['__id__']: continue else: for mod_, fchunk in six.iteritems(fchunks): if ( not isinstance(mod_, six.string_types) or mod_.startswith('__') ): continue else: if not isinstance(fchunk, list): continue else: # bydefault onfail will fail, but you can # set onfail_stop: False to prevent the highstate # to stop if you handle it onfail_handled = False for fdata in fchunk: if not isinstance(fdata, dict): continue onfail_handled = (fdata.get('onfail_stop', True) is False) if onfail_handled: break if not onfail_handled: continue for fdata in fchunk: if not isinstance(fdata, dict): continue for knob, fvalue in six.iteritems(fdata): if knob != 'onfail': continue for freqs in fvalue: for fmod, fid in six.iteritems(freqs): if not ( fid == st['__id__'] and fmod == st.get('state', fmod) ): continue onfails.append((fstate, mod_, fchunk)) return onfails def check_onfail_requisites(state_id, state_result, running, highstate): ''' When a state fail and is part of a highstate, check if there is onfail requisites. When we find onfail requisites, we will consider the state failed only if at least one of those onfail requisites also failed Returns: True: if onfail handlers suceeded False: if one on those handler failed None: if the state does not have onfail requisites ''' nret = None if ( state_id and state_result and highstate and isinstance(highstate, dict) ): onfails = search_onfail_requisites(state_id, highstate) if onfails: for handler in onfails: fstate, mod_, fchunk = handler for rstateid, rstate in six.iteritems(running): if '_|-' in rstateid: st = salt.state.split_low_tag(rstateid) # in case of simple state, try to guess else: id_ = rstate.get('__id__', rstateid) if not id_: raise ValueError('no state id') st = {'__id__': id_, 'state': mod_} if mod_ == st['state'] and fstate == st['__id__']: ofresult = rstate.get('result', _empty) if ofresult in [False, True]: nret = ofresult if ofresult is False: # as soon as we find an errored onfail, we stop break # consider that if we parsed onfailes without changing # the ret, that we have failed if nret is None: nret = False return nret def check_result(running, recurse=False, highstate=None): ''' Check the total return value of the run and determine if the running dict has any issues ''' if not isinstance(running, dict): return False if not running: return False ret = True for state_id, state_result in six.iteritems(running): expected_type = dict # The __extend__ state is a list if "__extend__" == state_id: expected_type = list if not recurse and not isinstance(state_result, expected_type): ret = False if ret and isinstance(state_result, dict): result = state_result.get('result', _empty) if result is False: ret = False # only override return value if we are not already failed elif result is _empty and isinstance(state_result, dict) and ret: ret = check_result( state_result, recurse=True, highstate=highstate) # if we detect a fail, check for onfail requisites if not ret: # ret can be None in case of no onfail reqs, recast it to bool ret = bool(check_onfail_requisites(state_id, state_result, running, highstate)) # return as soon as we got a failure if not ret: break return ret def get_sls_opts(opts, **kwargs): ''' Return a copy of the opts for use, optionally load a local config on top ''' opts = copy.deepcopy(opts) if 'localconfig' in kwargs: return salt.config.minion_config(kwargs['localconfig'], defaults=opts) if 'saltenv' in kwargs: saltenv = kwargs['saltenv'] if saltenv is not None: if not isinstance(saltenv, six.string_types): saltenv = six.text_type(saltenv) if opts['lock_saltenv'] and saltenv != opts['saltenv']: raise CommandExecutionError( 'lock_saltenv is enabled, saltenv cannot be changed' ) opts['saltenv'] = kwargs['saltenv'] pillarenv = None if kwargs.get('pillarenv'): pillarenv = kwargs.get('pillarenv') if opts.get('pillarenv_from_saltenv') and not pillarenv: pillarenv = kwargs.get('saltenv') if pillarenv is not None and not isinstance(pillarenv, six.string_types): opts['pillarenv'] = six.text_type(pillarenv) else: opts['pillarenv'] = pillarenv return opts
saltstack/salt
salt/utils/state.py
get_sls_opts
python
def get_sls_opts(opts, **kwargs): ''' Return a copy of the opts for use, optionally load a local config on top ''' opts = copy.deepcopy(opts) if 'localconfig' in kwargs: return salt.config.minion_config(kwargs['localconfig'], defaults=opts) if 'saltenv' in kwargs: saltenv = kwargs['saltenv'] if saltenv is not None: if not isinstance(saltenv, six.string_types): saltenv = six.text_type(saltenv) if opts['lock_saltenv'] and saltenv != opts['saltenv']: raise CommandExecutionError( 'lock_saltenv is enabled, saltenv cannot be changed' ) opts['saltenv'] = kwargs['saltenv'] pillarenv = None if kwargs.get('pillarenv'): pillarenv = kwargs.get('pillarenv') if opts.get('pillarenv_from_saltenv') and not pillarenv: pillarenv = kwargs.get('saltenv') if pillarenv is not None and not isinstance(pillarenv, six.string_types): opts['pillarenv'] = six.text_type(pillarenv) else: opts['pillarenv'] = pillarenv return opts
Return a copy of the opts for use, optionally load a local config on top
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/state.py#L218-L248
[ "def minion_config(path,\n env_var='SALT_MINION_CONFIG',\n defaults=None,\n cache_minion_id=False,\n ignore_config_errors=True,\n minion_id=None,\n role='minion'):\n '''\n Reads in the minion configuration file and sets up special options\n\n This is useful for Minion-side operations, such as the\n :py:class:`~salt.client.Caller` class, and manually running the loader\n interface.\n\n .. code-block:: python\n\n import salt.config\n minion_opts = salt.config.minion_config('/etc/salt/minion')\n '''\n if defaults is None:\n defaults = DEFAULT_MINION_OPTS.copy()\n\n if not os.environ.get(env_var, None):\n # No valid setting was given using the configuration variable.\n # Lets see is SALT_CONFIG_DIR is of any use\n salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)\n if salt_config_dir:\n env_config_file_path = os.path.join(salt_config_dir, 'minion')\n if salt_config_dir and os.path.isfile(env_config_file_path):\n # We can get a configuration file using SALT_CONFIG_DIR, let's\n # update the environment with this information\n os.environ[env_var] = env_config_file_path\n\n overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])\n default_include = overrides.get('default_include',\n defaults['default_include'])\n include = overrides.get('include', [])\n\n overrides.update(include_config(default_include, path, verbose=False,\n exit_on_config_errors=not ignore_config_errors))\n overrides.update(include_config(include, path, verbose=True,\n exit_on_config_errors=not ignore_config_errors))\n\n opts = apply_minion_config(overrides, defaults,\n cache_minion_id=cache_minion_id,\n minion_id=minion_id)\n opts['__role'] = role\n apply_sdb(opts)\n _validate_opts(opts)\n return opts\n" ]
# -*- coding: utf-8 -*- ''' Utility functions for state functions .. versionadded:: 2018.3.0 ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import copy # Import Salt libs from salt.ext import six from salt.exceptions import CommandExecutionError import salt.state _empty = object() def gen_tag(low): ''' Generate the running dict tag string from the low data structure ''' return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low) def search_onfail_requisites(sid, highstate): ''' For a particular low chunk, search relevant onfail related states ''' onfails = [] if '_|-' in sid: st = salt.state.split_low_tag(sid) else: st = {'__id__': sid} for fstate, fchunks in six.iteritems(highstate): if fstate == st['__id__']: continue else: for mod_, fchunk in six.iteritems(fchunks): if ( not isinstance(mod_, six.string_types) or mod_.startswith('__') ): continue else: if not isinstance(fchunk, list): continue else: # bydefault onfail will fail, but you can # set onfail_stop: False to prevent the highstate # to stop if you handle it onfail_handled = False for fdata in fchunk: if not isinstance(fdata, dict): continue onfail_handled = (fdata.get('onfail_stop', True) is False) if onfail_handled: break if not onfail_handled: continue for fdata in fchunk: if not isinstance(fdata, dict): continue for knob, fvalue in six.iteritems(fdata): if knob != 'onfail': continue for freqs in fvalue: for fmod, fid in six.iteritems(freqs): if not ( fid == st['__id__'] and fmod == st.get('state', fmod) ): continue onfails.append((fstate, mod_, fchunk)) return onfails def check_onfail_requisites(state_id, state_result, running, highstate): ''' When a state fail and is part of a highstate, check if there is onfail requisites. When we find onfail requisites, we will consider the state failed only if at least one of those onfail requisites also failed Returns: True: if onfail handlers suceeded False: if one on those handler failed None: if the state does not have onfail requisites ''' nret = None if ( state_id and state_result and highstate and isinstance(highstate, dict) ): onfails = search_onfail_requisites(state_id, highstate) if onfails: for handler in onfails: fstate, mod_, fchunk = handler for rstateid, rstate in six.iteritems(running): if '_|-' in rstateid: st = salt.state.split_low_tag(rstateid) # in case of simple state, try to guess else: id_ = rstate.get('__id__', rstateid) if not id_: raise ValueError('no state id') st = {'__id__': id_, 'state': mod_} if mod_ == st['state'] and fstate == st['__id__']: ofresult = rstate.get('result', _empty) if ofresult in [False, True]: nret = ofresult if ofresult is False: # as soon as we find an errored onfail, we stop break # consider that if we parsed onfailes without changing # the ret, that we have failed if nret is None: nret = False return nret def check_result(running, recurse=False, highstate=None): ''' Check the total return value of the run and determine if the running dict has any issues ''' if not isinstance(running, dict): return False if not running: return False ret = True for state_id, state_result in six.iteritems(running): expected_type = dict # The __extend__ state is a list if "__extend__" == state_id: expected_type = list if not recurse and not isinstance(state_result, expected_type): ret = False if ret and isinstance(state_result, dict): result = state_result.get('result', _empty) if result is False: ret = False # only override return value if we are not already failed elif result is _empty and isinstance(state_result, dict) and ret: ret = check_result( state_result, recurse=True, highstate=highstate) # if we detect a fail, check for onfail requisites if not ret: # ret can be None in case of no onfail reqs, recast it to bool ret = bool(check_onfail_requisites(state_id, state_result, running, highstate)) # return as soon as we got a failure if not ret: break return ret def merge_subreturn(original_return, sub_return, subkey=None): ''' Update an existing state return (`original_return`) in place with another state return (`sub_return`), i.e. for a subresource. Returns: dict: The updated state return. The existing state return does not need to have all the required fields, as this is meant to be called from the internals of a state function, but any existing data will be kept and respected. It is important after using this function to check the return value to see if it is False, in which case the main state should return. Prefer to check `_ret['result']` instead of `ret['result']`, as the latter field may not yet be populated. Code Example: .. code-block:: python def state_func(name, config, alarm=None): ret = {'name': name, 'comment': '', 'changes': {}} if alarm: _ret = __states__['subresource.managed'](alarm) __utils__['state.merge_subreturn'](ret, _ret) if _ret['result'] is False: return ret ''' if not subkey: subkey = sub_return['name'] if sub_return['result'] is False: # True or None stay the same original_return['result'] = sub_return['result'] sub_comment = sub_return['comment'] if not isinstance(sub_comment, list): sub_comment = [sub_comment] original_return.setdefault('comment', []) if isinstance(original_return['comment'], list): original_return['comment'].extend(sub_comment) else: if original_return['comment']: # Skip for empty original comments original_return['comment'] += '\n' original_return['comment'] += '\n'.join(sub_comment) if sub_return['changes']: # changes always exists original_return.setdefault('changes', {}) original_return['changes'][subkey] = sub_return['changes'] return original_return
saltstack/salt
salt/modules/deb_apache.py
check_site_enabled
python
def check_site_enabled(site): ''' Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com salt '*' apache.check_site_enabled example.com.conf ''' if site.endswith('.conf'): site_file = site else: site_file = '{0}.conf'.format(site) if os.path.islink('{0}/{1}'.format(SITE_ENABLED_DIR, site_file)): return True elif site == 'default' and \ os.path.islink('{0}/000-{1}'.format(SITE_ENABLED_DIR, site_file)): return True else: return False
Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com salt '*' apache.check_site_enabled example.com.conf
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_apache.py#L49-L73
null
# -*- coding: utf-8 -*- ''' Support for Apache Please note: The functions in here are Debian-specific. Placing them in this separate file will allow them to load only on Debian-based systems, while still loading under the ``apache`` namespace. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import logging # Import salt libs import salt.utils.decorators.path import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = 'apache' SITE_ENABLED_DIR = '/etc/apache2/sites-enabled' def __virtual__(): ''' Only load the module if apache is installed ''' cmd = _detect_os() if salt.utils.path.which(cmd) and __grains__['os_family'] == 'Debian': return __virtualname__ return (False, 'apache execution module not loaded: apache not installed.') def _detect_os(): ''' Apache commands and paths differ depending on packaging ''' # TODO: Add pillar support for the apachectl location if __grains__['os_family'] == 'RedHat': return 'apachectl' elif __grains__['os_family'] == 'Debian': return 'apache2ctl' else: return 'apachectl' def a2ensite(site): ''' Runs a2ensite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2ensite example.com ''' ret = {} command = ['a2ensite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Site' ret['Site'] = site if status == 1: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} enabled'.format(site) else: ret['Status'] = status return ret def a2dissite(site): ''' Runs a2dissite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dissite example.com ''' ret = {} command = ['a2dissite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Site' ret['Site'] = site if status == 256: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} disabled'.format(site) else: ret['Status'] = status return ret def check_mod_enabled(mod): ''' Checks to see if the specific mod symlink is in /etc/apache2/mods-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_mod_enabled status salt '*' apache.check_mod_enabled status.load salt '*' apache.check_mod_enabled status.conf ''' if mod.endswith('.load') or mod.endswith('.conf'): mod_file = mod else: mod_file = '{0}.load'.format(mod) return os.path.islink('/etc/apache2/mods-enabled/{0}'.format(mod_file)) def a2enmod(mod): ''' Runs a2enmod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enmod vhost_alias ''' ret = {} command = ['a2enmod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Mod' ret['Mod'] = mod if status == 1: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} enabled'.format(mod) else: ret['Status'] = status return ret def a2dismod(mod): ''' Runs a2dismod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dismod vhost_alias ''' ret = {} command = ['a2dismod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Mod' ret['Mod'] = mod if status == 256: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} disabled'.format(mod) else: ret['Status'] = status return ret def check_conf_enabled(conf): ''' .. versionadded:: 2016.3.0 Checks to see if the specific conf symlink is in /etc/apache2/conf-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_conf_enabled security salt '*' apache.check_conf_enabled security.conf ''' if conf.endswith('.conf'): conf_file = conf else: conf_file = '{0}.conf'.format(conf) return os.path.islink('/etc/apache2/conf-enabled/{0}'.format(conf_file)) @salt.utils.decorators.path.which('a2enconf') def a2enconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2enconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enconf security ''' ret = {} command = ['a2enconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Conf' ret['Conf'] = conf if status == 1: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} enabled'.format(conf) else: ret['Status'] = status return ret @salt.utils.decorators.path.which('a2disconf') def a2disconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2disconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2disconf security ''' ret = {} command = ['a2disconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Conf' ret['Conf'] = conf if status == 256: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} disabled'.format(conf) else: ret['Status'] = status return ret
saltstack/salt
salt/modules/deb_apache.py
a2dissite
python
def a2dissite(site): ''' Runs a2dissite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dissite example.com ''' ret = {} command = ['a2dissite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Site' ret['Site'] = site if status == 256: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} disabled'.format(site) else: ret['Status'] = status return ret
Runs a2dissite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dissite example.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_apache.py#L110-L141
null
# -*- coding: utf-8 -*- ''' Support for Apache Please note: The functions in here are Debian-specific. Placing them in this separate file will allow them to load only on Debian-based systems, while still loading under the ``apache`` namespace. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import logging # Import salt libs import salt.utils.decorators.path import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = 'apache' SITE_ENABLED_DIR = '/etc/apache2/sites-enabled' def __virtual__(): ''' Only load the module if apache is installed ''' cmd = _detect_os() if salt.utils.path.which(cmd) and __grains__['os_family'] == 'Debian': return __virtualname__ return (False, 'apache execution module not loaded: apache not installed.') def _detect_os(): ''' Apache commands and paths differ depending on packaging ''' # TODO: Add pillar support for the apachectl location if __grains__['os_family'] == 'RedHat': return 'apachectl' elif __grains__['os_family'] == 'Debian': return 'apache2ctl' else: return 'apachectl' def check_site_enabled(site): ''' Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com salt '*' apache.check_site_enabled example.com.conf ''' if site.endswith('.conf'): site_file = site else: site_file = '{0}.conf'.format(site) if os.path.islink('{0}/{1}'.format(SITE_ENABLED_DIR, site_file)): return True elif site == 'default' and \ os.path.islink('{0}/000-{1}'.format(SITE_ENABLED_DIR, site_file)): return True else: return False def a2ensite(site): ''' Runs a2ensite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2ensite example.com ''' ret = {} command = ['a2ensite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Site' ret['Site'] = site if status == 1: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} enabled'.format(site) else: ret['Status'] = status return ret def check_mod_enabled(mod): ''' Checks to see if the specific mod symlink is in /etc/apache2/mods-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_mod_enabled status salt '*' apache.check_mod_enabled status.load salt '*' apache.check_mod_enabled status.conf ''' if mod.endswith('.load') or mod.endswith('.conf'): mod_file = mod else: mod_file = '{0}.load'.format(mod) return os.path.islink('/etc/apache2/mods-enabled/{0}'.format(mod_file)) def a2enmod(mod): ''' Runs a2enmod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enmod vhost_alias ''' ret = {} command = ['a2enmod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Mod' ret['Mod'] = mod if status == 1: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} enabled'.format(mod) else: ret['Status'] = status return ret def a2dismod(mod): ''' Runs a2dismod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dismod vhost_alias ''' ret = {} command = ['a2dismod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Mod' ret['Mod'] = mod if status == 256: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} disabled'.format(mod) else: ret['Status'] = status return ret def check_conf_enabled(conf): ''' .. versionadded:: 2016.3.0 Checks to see if the specific conf symlink is in /etc/apache2/conf-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_conf_enabled security salt '*' apache.check_conf_enabled security.conf ''' if conf.endswith('.conf'): conf_file = conf else: conf_file = '{0}.conf'.format(conf) return os.path.islink('/etc/apache2/conf-enabled/{0}'.format(conf_file)) @salt.utils.decorators.path.which('a2enconf') def a2enconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2enconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enconf security ''' ret = {} command = ['a2enconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Conf' ret['Conf'] = conf if status == 1: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} enabled'.format(conf) else: ret['Status'] = status return ret @salt.utils.decorators.path.which('a2disconf') def a2disconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2disconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2disconf security ''' ret = {} command = ['a2disconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Conf' ret['Conf'] = conf if status == 256: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} disabled'.format(conf) else: ret['Status'] = status return ret
saltstack/salt
salt/modules/deb_apache.py
check_mod_enabled
python
def check_mod_enabled(mod): ''' Checks to see if the specific mod symlink is in /etc/apache2/mods-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_mod_enabled status salt '*' apache.check_mod_enabled status.load salt '*' apache.check_mod_enabled status.conf ''' if mod.endswith('.load') or mod.endswith('.conf'): mod_file = mod else: mod_file = '{0}.load'.format(mod) return os.path.islink('/etc/apache2/mods-enabled/{0}'.format(mod_file))
Checks to see if the specific mod symlink is in /etc/apache2/mods-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_mod_enabled status salt '*' apache.check_mod_enabled status.load salt '*' apache.check_mod_enabled status.conf
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_apache.py#L144-L163
null
# -*- coding: utf-8 -*- ''' Support for Apache Please note: The functions in here are Debian-specific. Placing them in this separate file will allow them to load only on Debian-based systems, while still loading under the ``apache`` namespace. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import logging # Import salt libs import salt.utils.decorators.path import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = 'apache' SITE_ENABLED_DIR = '/etc/apache2/sites-enabled' def __virtual__(): ''' Only load the module if apache is installed ''' cmd = _detect_os() if salt.utils.path.which(cmd) and __grains__['os_family'] == 'Debian': return __virtualname__ return (False, 'apache execution module not loaded: apache not installed.') def _detect_os(): ''' Apache commands and paths differ depending on packaging ''' # TODO: Add pillar support for the apachectl location if __grains__['os_family'] == 'RedHat': return 'apachectl' elif __grains__['os_family'] == 'Debian': return 'apache2ctl' else: return 'apachectl' def check_site_enabled(site): ''' Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com salt '*' apache.check_site_enabled example.com.conf ''' if site.endswith('.conf'): site_file = site else: site_file = '{0}.conf'.format(site) if os.path.islink('{0}/{1}'.format(SITE_ENABLED_DIR, site_file)): return True elif site == 'default' and \ os.path.islink('{0}/000-{1}'.format(SITE_ENABLED_DIR, site_file)): return True else: return False def a2ensite(site): ''' Runs a2ensite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2ensite example.com ''' ret = {} command = ['a2ensite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Site' ret['Site'] = site if status == 1: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} enabled'.format(site) else: ret['Status'] = status return ret def a2dissite(site): ''' Runs a2dissite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dissite example.com ''' ret = {} command = ['a2dissite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Site' ret['Site'] = site if status == 256: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} disabled'.format(site) else: ret['Status'] = status return ret def a2enmod(mod): ''' Runs a2enmod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enmod vhost_alias ''' ret = {} command = ['a2enmod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Mod' ret['Mod'] = mod if status == 1: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} enabled'.format(mod) else: ret['Status'] = status return ret def a2dismod(mod): ''' Runs a2dismod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dismod vhost_alias ''' ret = {} command = ['a2dismod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Mod' ret['Mod'] = mod if status == 256: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} disabled'.format(mod) else: ret['Status'] = status return ret def check_conf_enabled(conf): ''' .. versionadded:: 2016.3.0 Checks to see if the specific conf symlink is in /etc/apache2/conf-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_conf_enabled security salt '*' apache.check_conf_enabled security.conf ''' if conf.endswith('.conf'): conf_file = conf else: conf_file = '{0}.conf'.format(conf) return os.path.islink('/etc/apache2/conf-enabled/{0}'.format(conf_file)) @salt.utils.decorators.path.which('a2enconf') def a2enconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2enconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enconf security ''' ret = {} command = ['a2enconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Conf' ret['Conf'] = conf if status == 1: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} enabled'.format(conf) else: ret['Status'] = status return ret @salt.utils.decorators.path.which('a2disconf') def a2disconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2disconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2disconf security ''' ret = {} command = ['a2disconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Conf' ret['Conf'] = conf if status == 256: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} disabled'.format(conf) else: ret['Status'] = status return ret
saltstack/salt
salt/modules/deb_apache.py
a2enmod
python
def a2enmod(mod): ''' Runs a2enmod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enmod vhost_alias ''' ret = {} command = ['a2enmod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Mod' ret['Mod'] = mod if status == 1: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} enabled'.format(mod) else: ret['Status'] = status return ret
Runs a2enmod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enmod vhost_alias
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_apache.py#L166-L197
null
# -*- coding: utf-8 -*- ''' Support for Apache Please note: The functions in here are Debian-specific. Placing them in this separate file will allow them to load only on Debian-based systems, while still loading under the ``apache`` namespace. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import logging # Import salt libs import salt.utils.decorators.path import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = 'apache' SITE_ENABLED_DIR = '/etc/apache2/sites-enabled' def __virtual__(): ''' Only load the module if apache is installed ''' cmd = _detect_os() if salt.utils.path.which(cmd) and __grains__['os_family'] == 'Debian': return __virtualname__ return (False, 'apache execution module not loaded: apache not installed.') def _detect_os(): ''' Apache commands and paths differ depending on packaging ''' # TODO: Add pillar support for the apachectl location if __grains__['os_family'] == 'RedHat': return 'apachectl' elif __grains__['os_family'] == 'Debian': return 'apache2ctl' else: return 'apachectl' def check_site_enabled(site): ''' Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com salt '*' apache.check_site_enabled example.com.conf ''' if site.endswith('.conf'): site_file = site else: site_file = '{0}.conf'.format(site) if os.path.islink('{0}/{1}'.format(SITE_ENABLED_DIR, site_file)): return True elif site == 'default' and \ os.path.islink('{0}/000-{1}'.format(SITE_ENABLED_DIR, site_file)): return True else: return False def a2ensite(site): ''' Runs a2ensite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2ensite example.com ''' ret = {} command = ['a2ensite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Site' ret['Site'] = site if status == 1: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} enabled'.format(site) else: ret['Status'] = status return ret def a2dissite(site): ''' Runs a2dissite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dissite example.com ''' ret = {} command = ['a2dissite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Site' ret['Site'] = site if status == 256: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} disabled'.format(site) else: ret['Status'] = status return ret def check_mod_enabled(mod): ''' Checks to see if the specific mod symlink is in /etc/apache2/mods-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_mod_enabled status salt '*' apache.check_mod_enabled status.load salt '*' apache.check_mod_enabled status.conf ''' if mod.endswith('.load') or mod.endswith('.conf'): mod_file = mod else: mod_file = '{0}.load'.format(mod) return os.path.islink('/etc/apache2/mods-enabled/{0}'.format(mod_file)) def a2dismod(mod): ''' Runs a2dismod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dismod vhost_alias ''' ret = {} command = ['a2dismod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Mod' ret['Mod'] = mod if status == 256: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} disabled'.format(mod) else: ret['Status'] = status return ret def check_conf_enabled(conf): ''' .. versionadded:: 2016.3.0 Checks to see if the specific conf symlink is in /etc/apache2/conf-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_conf_enabled security salt '*' apache.check_conf_enabled security.conf ''' if conf.endswith('.conf'): conf_file = conf else: conf_file = '{0}.conf'.format(conf) return os.path.islink('/etc/apache2/conf-enabled/{0}'.format(conf_file)) @salt.utils.decorators.path.which('a2enconf') def a2enconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2enconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enconf security ''' ret = {} command = ['a2enconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Conf' ret['Conf'] = conf if status == 1: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} enabled'.format(conf) else: ret['Status'] = status return ret @salt.utils.decorators.path.which('a2disconf') def a2disconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2disconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2disconf security ''' ret = {} command = ['a2disconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Conf' ret['Conf'] = conf if status == 256: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} disabled'.format(conf) else: ret['Status'] = status return ret
saltstack/salt
salt/modules/deb_apache.py
check_conf_enabled
python
def check_conf_enabled(conf): ''' .. versionadded:: 2016.3.0 Checks to see if the specific conf symlink is in /etc/apache2/conf-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_conf_enabled security salt '*' apache.check_conf_enabled security.conf ''' if conf.endswith('.conf'): conf_file = conf else: conf_file = '{0}.conf'.format(conf) return os.path.islink('/etc/apache2/conf-enabled/{0}'.format(conf_file))
.. versionadded:: 2016.3.0 Checks to see if the specific conf symlink is in /etc/apache2/conf-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_conf_enabled security salt '*' apache.check_conf_enabled security.conf
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_apache.py#L234-L254
null
# -*- coding: utf-8 -*- ''' Support for Apache Please note: The functions in here are Debian-specific. Placing them in this separate file will allow them to load only on Debian-based systems, while still loading under the ``apache`` namespace. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import logging # Import salt libs import salt.utils.decorators.path import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = 'apache' SITE_ENABLED_DIR = '/etc/apache2/sites-enabled' def __virtual__(): ''' Only load the module if apache is installed ''' cmd = _detect_os() if salt.utils.path.which(cmd) and __grains__['os_family'] == 'Debian': return __virtualname__ return (False, 'apache execution module not loaded: apache not installed.') def _detect_os(): ''' Apache commands and paths differ depending on packaging ''' # TODO: Add pillar support for the apachectl location if __grains__['os_family'] == 'RedHat': return 'apachectl' elif __grains__['os_family'] == 'Debian': return 'apache2ctl' else: return 'apachectl' def check_site_enabled(site): ''' Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com salt '*' apache.check_site_enabled example.com.conf ''' if site.endswith('.conf'): site_file = site else: site_file = '{0}.conf'.format(site) if os.path.islink('{0}/{1}'.format(SITE_ENABLED_DIR, site_file)): return True elif site == 'default' and \ os.path.islink('{0}/000-{1}'.format(SITE_ENABLED_DIR, site_file)): return True else: return False def a2ensite(site): ''' Runs a2ensite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2ensite example.com ''' ret = {} command = ['a2ensite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Site' ret['Site'] = site if status == 1: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} enabled'.format(site) else: ret['Status'] = status return ret def a2dissite(site): ''' Runs a2dissite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dissite example.com ''' ret = {} command = ['a2dissite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Site' ret['Site'] = site if status == 256: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} disabled'.format(site) else: ret['Status'] = status return ret def check_mod_enabled(mod): ''' Checks to see if the specific mod symlink is in /etc/apache2/mods-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_mod_enabled status salt '*' apache.check_mod_enabled status.load salt '*' apache.check_mod_enabled status.conf ''' if mod.endswith('.load') or mod.endswith('.conf'): mod_file = mod else: mod_file = '{0}.load'.format(mod) return os.path.islink('/etc/apache2/mods-enabled/{0}'.format(mod_file)) def a2enmod(mod): ''' Runs a2enmod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enmod vhost_alias ''' ret = {} command = ['a2enmod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Mod' ret['Mod'] = mod if status == 1: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} enabled'.format(mod) else: ret['Status'] = status return ret def a2dismod(mod): ''' Runs a2dismod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dismod vhost_alias ''' ret = {} command = ['a2dismod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Mod' ret['Mod'] = mod if status == 256: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} disabled'.format(mod) else: ret['Status'] = status return ret @salt.utils.decorators.path.which('a2enconf') def a2enconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2enconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enconf security ''' ret = {} command = ['a2enconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Conf' ret['Conf'] = conf if status == 1: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} enabled'.format(conf) else: ret['Status'] = status return ret @salt.utils.decorators.path.which('a2disconf') def a2disconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2disconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2disconf security ''' ret = {} command = ['a2disconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Conf' ret['Conf'] = conf if status == 256: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} disabled'.format(conf) else: ret['Status'] = status return ret
saltstack/salt
salt/modules/deb_apache.py
a2enconf
python
def a2enconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2enconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enconf security ''' ret = {} command = ['a2enconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Conf' ret['Conf'] = conf if status == 1: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} enabled'.format(conf) else: ret['Status'] = status return ret
.. versionadded:: 2016.3.0 Runs a2enconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enconf security
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_apache.py#L258-L291
null
# -*- coding: utf-8 -*- ''' Support for Apache Please note: The functions in here are Debian-specific. Placing them in this separate file will allow them to load only on Debian-based systems, while still loading under the ``apache`` namespace. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import logging # Import salt libs import salt.utils.decorators.path import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = 'apache' SITE_ENABLED_DIR = '/etc/apache2/sites-enabled' def __virtual__(): ''' Only load the module if apache is installed ''' cmd = _detect_os() if salt.utils.path.which(cmd) and __grains__['os_family'] == 'Debian': return __virtualname__ return (False, 'apache execution module not loaded: apache not installed.') def _detect_os(): ''' Apache commands and paths differ depending on packaging ''' # TODO: Add pillar support for the apachectl location if __grains__['os_family'] == 'RedHat': return 'apachectl' elif __grains__['os_family'] == 'Debian': return 'apache2ctl' else: return 'apachectl' def check_site_enabled(site): ''' Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com salt '*' apache.check_site_enabled example.com.conf ''' if site.endswith('.conf'): site_file = site else: site_file = '{0}.conf'.format(site) if os.path.islink('{0}/{1}'.format(SITE_ENABLED_DIR, site_file)): return True elif site == 'default' and \ os.path.islink('{0}/000-{1}'.format(SITE_ENABLED_DIR, site_file)): return True else: return False def a2ensite(site): ''' Runs a2ensite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2ensite example.com ''' ret = {} command = ['a2ensite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Site' ret['Site'] = site if status == 1: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} enabled'.format(site) else: ret['Status'] = status return ret def a2dissite(site): ''' Runs a2dissite for the given site. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dissite example.com ''' ret = {} command = ['a2dissite', site] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Site' ret['Site'] = site if status == 256: ret['Status'] = 'Site {0} Not found'.format(site) elif status == 0: ret['Status'] = 'Site {0} disabled'.format(site) else: ret['Status'] = status return ret def check_mod_enabled(mod): ''' Checks to see if the specific mod symlink is in /etc/apache2/mods-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_mod_enabled status salt '*' apache.check_mod_enabled status.load salt '*' apache.check_mod_enabled status.conf ''' if mod.endswith('.load') or mod.endswith('.conf'): mod_file = mod else: mod_file = '{0}.load'.format(mod) return os.path.islink('/etc/apache2/mods-enabled/{0}'.format(mod_file)) def a2enmod(mod): ''' Runs a2enmod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2enmod vhost_alias ''' ret = {} command = ['a2enmod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Mod' ret['Mod'] = mod if status == 1: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} enabled'.format(mod) else: ret['Status'] = status return ret def a2dismod(mod): ''' Runs a2dismod for the given mod. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2dismod vhost_alias ''' ret = {} command = ['a2dismod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Mod' ret['Mod'] = mod if status == 256: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} disabled'.format(mod) else: ret['Status'] = status return ret def check_conf_enabled(conf): ''' .. versionadded:: 2016.3.0 Checks to see if the specific conf symlink is in /etc/apache2/conf-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_conf_enabled security salt '*' apache.check_conf_enabled security.conf ''' if conf.endswith('.conf'): conf_file = conf else: conf_file = '{0}.conf'.format(conf) return os.path.islink('/etc/apache2/conf-enabled/{0}'.format(conf_file)) @salt.utils.decorators.path.which('a2enconf') @salt.utils.decorators.path.which('a2disconf') def a2disconf(conf): ''' .. versionadded:: 2016.3.0 Runs a2disconf for the given conf. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.a2disconf security ''' ret = {} command = ['a2disconf', conf] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Conf' ret['Conf'] = conf if status == 256: ret['Status'] = 'Conf {0} Not found'.format(conf) elif status == 0: ret['Status'] = 'Conf {0} disabled'.format(conf) else: ret['Status'] = status return ret
saltstack/salt
salt/modules/uwsgi.py
stats
python
def stats(socket): ''' Return the data from `uwsgi --connect-and-read` as a dictionary. socket The socket the uWSGI stats server is listening on CLI Example: .. code-block:: bash salt '*' uwsgi.stats /var/run/mystatsserver.sock salt '*' uwsgi.stats 127.0.0.1:5050 ''' cmd = ['uwsgi', '--connect-and-read', '{0}'.format(socket)] out = __salt__['cmd.run'](cmd, python_shell=False) return salt.utils.json.loads(out)
Return the data from `uwsgi --connect-and-read` as a dictionary. socket The socket the uWSGI stats server is listening on CLI Example: .. code-block:: bash salt '*' uwsgi.stats /var/run/mystatsserver.sock salt '*' uwsgi.stats 127.0.0.1:5050
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/uwsgi.py#L27-L45
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' uWSGI stats server https://uwsgi-docs.readthedocs.io/en/latest/StatsServer.html :maintainer: Peter Baumgartner <pete@lincolnloop.com> :maturity: new :platform: all ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.json import salt.utils.path def __virtual__(): ''' Only load the module if uwsgi is installed ''' cmd = 'uwsgi' if salt.utils.path.which(cmd): return cmd return (False, 'The uwsgi execution module failed to load: the uwsgi binary is not in the path.')
saltstack/salt
salt/grains/fx2.py
_find_credentials
python
def _find_credentials(): ''' Cycle through all the possible credentials and return the first one that works ''' usernames = [] usernames.append(__pillar__['proxy'].get('admin_username', 'root')) if 'fallback_admin_username' in __pillar__.get('proxy'): usernames.append(__pillar__['proxy'].get('fallback_admin_username')) for user in usernames: for pwd in __pillar__['proxy']['passwords']: r = salt.modules.dracr.get_chassis_name( host=__pillar__['proxy']['host'], admin_username=user, admin_password=pwd) # Retcode will be present if the chassis_name call failed try: if r.get('retcode', None) is None: __opts__['proxy']['admin_username'] = user __opts__['proxy']['admin_password'] = pwd return (user, pwd) except AttributeError: # Then the above was a string, and we can return the username # and password __opts__['proxy']['admin_username'] = user __opts__['proxy']['admin_password'] = pwd return (user, pwd) logger.debug('grains fx2.find_credentials found no valid credentials, using Dell default') return ('root', 'calvin')
Cycle through all the possible credentials and return the first one that works
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/fx2.py#L32-L62
[ "def get_chassis_name(host=None, admin_username=None, admin_password=None):\n '''\n Get the name of a chassis.\n\n host\n The chassis host.\n\n admin_username\n The username used to access the chassis.\n\n admin_password\n The password used to access the chassis.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' dracr.get_chassis_name host=111.222.333.444\n admin_username=root admin_password=secret\n\n '''\n return bare_rac_cmd('getchassisname', host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n" ]
# -*- coding: utf-8 -*- ''' Generate baseline proxy minion grains for Dell FX2 chassis. The challenge is that most of Salt isn't bootstrapped yet, so we need to repeat a bunch of things that would normally happen in proxy/fx2.py--just enough to get data from the chassis to include in grains. ''' from __future__ import absolute_import, print_function, unicode_literals import logging import salt.proxy.fx2 import salt.modules.cmdmod import salt.modules.dracr import salt.utils.platform __proxyenabled__ = ['fx2'] __virtualname__ = 'fx2' logger = logging.getLogger(__file__) GRAINS_CACHE = {} def __virtual__(): if salt.utils.platform.is_proxy() and 'proxy' in __opts__ and __opts__['proxy'].get('proxytype') == 'fx2': return __virtualname__ return False def _grains(): ''' Get the grains from the proxied device ''' (username, password) = _find_credentials() r = salt.modules.dracr.system_info(host=__pillar__['proxy']['host'], admin_username=username, admin_password=password) if r.get('retcode', 0) == 0: GRAINS_CACHE = r else: GRAINS_CACHE = {} GRAINS_CACHE.update(salt.modules.dracr.inventory(host=__pillar__['proxy']['host'], admin_username=username, admin_password=password)) return GRAINS_CACHE def fx2(): return _grains() def kernel(): return {'kernel': 'proxy'} def location(): if not GRAINS_CACHE: GRAINS_CACHE.update(_grains()) try: return {'location': GRAINS_CACHE.get('Chassis Information').get('Chassis Location')} except AttributeError: return {'location': 'Unknown'} def os_family(): return {'os_family': 'proxy'} def os_data(): return {'os_data': 'Unknown'}
saltstack/salt
salt/grains/fx2.py
_grains
python
def _grains(): ''' Get the grains from the proxied device ''' (username, password) = _find_credentials() r = salt.modules.dracr.system_info(host=__pillar__['proxy']['host'], admin_username=username, admin_password=password) if r.get('retcode', 0) == 0: GRAINS_CACHE = r else: GRAINS_CACHE = {} GRAINS_CACHE.update(salt.modules.dracr.inventory(host=__pillar__['proxy']['host'], admin_username=username, admin_password=password)) return GRAINS_CACHE
Get the grains from the proxied device
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/fx2.py#L65-L83
[ "def inventory(host=None, admin_username=None, admin_password=None):\n def mapit(x, y):\n return {x: y}\n\n fields = {}\n fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',\n 'updateable']\n fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']\n fields['cmc'] = ['name', 'cmc_version', 'updateable']\n fields['chassis'] = ['name', 'fw_version', 'fqdd']\n\n rawinv = __execute_ret('getversion', host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n\n if rawinv['retcode'] != 0:\n return rawinv\n\n in_server = False\n in_switch = False\n in_cmc = False\n in_chassis = False\n ret = {}\n ret['server'] = {}\n ret['switch'] = {}\n ret['cmc'] = {}\n ret['chassis'] = {}\n for l in rawinv['stdout'].splitlines():\n if l.startswith('<Server>'):\n in_server = True\n in_switch = False\n in_cmc = False\n in_chassis = False\n continue\n\n if l.startswith('<Switch>'):\n in_server = False\n in_switch = True\n in_cmc = False\n in_chassis = False\n continue\n\n if l.startswith('<CMC>'):\n in_server = False\n in_switch = False\n in_cmc = True\n in_chassis = False\n continue\n\n if l.startswith('<Chassis Infrastructure>'):\n in_server = False\n in_switch = False\n in_cmc = False\n in_chassis = True\n continue\n\n if not l:\n continue\n\n line = re.split(' +', l.strip())\n\n if in_server:\n ret['server'][line[0]] = dict(\n (k, v) for d in map(mapit, fields['server'], line) for (k, v)\n in d.items())\n if in_switch:\n ret['switch'][line[0]] = dict(\n (k, v) for d in map(mapit, fields['switch'], line) for (k, v)\n in d.items())\n if in_cmc:\n ret['cmc'][line[0]] = dict(\n (k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in\n d.items())\n if in_chassis:\n ret['chassis'][line[0]] = dict(\n (k, v) for d in map(mapit, fields['chassis'], line) for k, v in\n d.items())\n\n return ret\n", "def system_info(host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Return System information\n\n CLI Example:\n\n .. code-block:: bash\n\n salt dell dracr.system_info\n '''\n cmd = __execute_ret('getsysinfo', host=host,\n admin_username=admin_username,\n admin_password=admin_password,\n module=module)\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return cmd\n\n return __parse_drac(cmd['stdout'])\n", "def _find_credentials():\n '''\n Cycle through all the possible credentials and return the first one that\n works\n '''\n usernames = []\n usernames.append(__pillar__['proxy'].get('admin_username', 'root'))\n if 'fallback_admin_username' in __pillar__.get('proxy'):\n usernames.append(__pillar__['proxy'].get('fallback_admin_username'))\n\n for user in usernames:\n for pwd in __pillar__['proxy']['passwords']:\n r = salt.modules.dracr.get_chassis_name(\n host=__pillar__['proxy']['host'],\n admin_username=user,\n admin_password=pwd)\n # Retcode will be present if the chassis_name call failed\n try:\n if r.get('retcode', None) is None:\n __opts__['proxy']['admin_username'] = user\n __opts__['proxy']['admin_password'] = pwd\n return (user, pwd)\n except AttributeError:\n # Then the above was a string, and we can return the username\n # and password\n __opts__['proxy']['admin_username'] = user\n __opts__['proxy']['admin_password'] = pwd\n return (user, pwd)\n\n logger.debug('grains fx2.find_credentials found no valid credentials, using Dell default')\n return ('root', 'calvin')\n" ]
# -*- coding: utf-8 -*- ''' Generate baseline proxy minion grains for Dell FX2 chassis. The challenge is that most of Salt isn't bootstrapped yet, so we need to repeat a bunch of things that would normally happen in proxy/fx2.py--just enough to get data from the chassis to include in grains. ''' from __future__ import absolute_import, print_function, unicode_literals import logging import salt.proxy.fx2 import salt.modules.cmdmod import salt.modules.dracr import salt.utils.platform __proxyenabled__ = ['fx2'] __virtualname__ = 'fx2' logger = logging.getLogger(__file__) GRAINS_CACHE = {} def __virtual__(): if salt.utils.platform.is_proxy() and 'proxy' in __opts__ and __opts__['proxy'].get('proxytype') == 'fx2': return __virtualname__ return False def _find_credentials(): ''' Cycle through all the possible credentials and return the first one that works ''' usernames = [] usernames.append(__pillar__['proxy'].get('admin_username', 'root')) if 'fallback_admin_username' in __pillar__.get('proxy'): usernames.append(__pillar__['proxy'].get('fallback_admin_username')) for user in usernames: for pwd in __pillar__['proxy']['passwords']: r = salt.modules.dracr.get_chassis_name( host=__pillar__['proxy']['host'], admin_username=user, admin_password=pwd) # Retcode will be present if the chassis_name call failed try: if r.get('retcode', None) is None: __opts__['proxy']['admin_username'] = user __opts__['proxy']['admin_password'] = pwd return (user, pwd) except AttributeError: # Then the above was a string, and we can return the username # and password __opts__['proxy']['admin_username'] = user __opts__['proxy']['admin_password'] = pwd return (user, pwd) logger.debug('grains fx2.find_credentials found no valid credentials, using Dell default') return ('root', 'calvin') def fx2(): return _grains() def kernel(): return {'kernel': 'proxy'} def location(): if not GRAINS_CACHE: GRAINS_CACHE.update(_grains()) try: return {'location': GRAINS_CACHE.get('Chassis Information').get('Chassis Location')} except AttributeError: return {'location': 'Unknown'} def os_family(): return {'os_family': 'proxy'} def os_data(): return {'os_data': 'Unknown'}
saltstack/salt
salt/modules/libcloud_storage.py
list_containers
python
def list_containers(profile, **libcloud_kwargs): ''' Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) containers = conn.list_containers(**libcloud_kwargs) ret = [] for container in containers: ret.append({ 'name': container.name, 'extra': container.extra }) return ret
Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L88-L113
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _get_driver(profile):\n config = __salt__['config.option']('libcloud_storage')[profile]\n cls = get_driver(config['driver'])\n args = config.copy()\n del args['driver']\n args['key'] = config.get('key')\n args['secret'] = config.get('secret', None)\n args['secure'] = config.get('secure', True)\n args['host'] = config.get('host', None)\n args['port'] = config.get('port', None)\n return cls(**args)\n" ]
# -*- coding: utf-8 -*- ''' Apache Libcloud Storage Management ================================== Connection module for Apache Libcloud Storage (object/blob) management for a full list of supported clouds, see http://libcloud.readthedocs.io/en/latest/storage/supported_providers.html Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack swift .. versionadded:: 2018.3.0 :configuration: This module uses a configuration profile for one or multiple Storage providers .. code-block:: yaml libcloud_storage: profile_test1: driver: google_storage key: GOOG0123456789ABCXYZ secret: mysecret profile_test2: driver: s3 key: 12345 secret: mysecret :depends: apache-libcloud ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs import salt.utils.args import salt.utils.compat from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) # Import third party libs REQUIRED_LIBCLOUD_VERSION = '1.5.0' try: #pylint: disable=unused-import import libcloud from libcloud.storage.providers import get_driver #pylint: enable=unused-import if hasattr(libcloud, '__version__') and _LooseVersion(libcloud.__version__) < _LooseVersion(REQUIRED_LIBCLOUD_VERSION): raise ImportError() logging.getLogger('libcloud').setLevel(logging.CRITICAL) HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False def __virtual__(): ''' Only load if libcloud libraries exist. ''' if not HAS_LIBCLOUD: msg = ('A apache-libcloud library with version at least {0} was not ' 'found').format(REQUIRED_LIBCLOUD_VERSION) return (False, msg) return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def _get_driver(profile): config = __salt__['config.option']('libcloud_storage')[profile] cls = get_driver(config['driver']) args = config.copy() del args['driver'] args['key'] = config.get('key') args['secret'] = config.get('secret', None) args['secure'] = config.get('secure', True) args['host'] = config.get('host', None) args['port'] = config.get('port', None) return cls(**args) def list_container_objects(container_name, profile, **libcloud_kwargs): ''' List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1 ''' conn = _get_driver(profile=profile) container = conn.get_container(container_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) objects = conn.list_container_objects(container, **libcloud_kwargs) ret = [] for obj in objects: ret.append({ 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data }) return ret def create_container(container_name, profile, **libcloud_kwargs): ''' Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.create_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container(container_name, profile, **libcloud_kwargs): ''' List container details for the given container_name on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container_object(container_name, object_name, profile, **libcloud_kwargs): ''' Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_container_object(container_name, object_name, **libcloud_kwargs) return { 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data} def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1 ''' conn = _get_driver(profile=profile) obj = conn.get_object(container_name, object_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs) def upload_object(file_path, container_name, object_name, profile, extra=None, verify_hash=True, headers=None, **libcloud_kwargs): ''' Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) obj = conn.upload_object(file_path, container, object_name, extra, verify_hash, headers, **libcloud_kwargs) return obj.name def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_object(container_name, object_name, **libcloud_kwargs) return conn.delete_object(obj) def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) return conn.delete_container(container, **libcloud_kwargs) def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
saltstack/salt
salt/modules/libcloud_storage.py
list_container_objects
python
def list_container_objects(container_name, profile, **libcloud_kwargs): ''' List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1 ''' conn = _get_driver(profile=profile) container = conn.get_container(container_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) objects = conn.list_container_objects(container, **libcloud_kwargs) ret = [] for obj in objects: ret.append({ 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data }) return ret
List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L116-L149
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _get_driver(profile):\n config = __salt__['config.option']('libcloud_storage')[profile]\n cls = get_driver(config['driver'])\n args = config.copy()\n del args['driver']\n args['key'] = config.get('key')\n args['secret'] = config.get('secret', None)\n args['secure'] = config.get('secure', True)\n args['host'] = config.get('host', None)\n args['port'] = config.get('port', None)\n return cls(**args)\n" ]
# -*- coding: utf-8 -*- ''' Apache Libcloud Storage Management ================================== Connection module for Apache Libcloud Storage (object/blob) management for a full list of supported clouds, see http://libcloud.readthedocs.io/en/latest/storage/supported_providers.html Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack swift .. versionadded:: 2018.3.0 :configuration: This module uses a configuration profile for one or multiple Storage providers .. code-block:: yaml libcloud_storage: profile_test1: driver: google_storage key: GOOG0123456789ABCXYZ secret: mysecret profile_test2: driver: s3 key: 12345 secret: mysecret :depends: apache-libcloud ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs import salt.utils.args import salt.utils.compat from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) # Import third party libs REQUIRED_LIBCLOUD_VERSION = '1.5.0' try: #pylint: disable=unused-import import libcloud from libcloud.storage.providers import get_driver #pylint: enable=unused-import if hasattr(libcloud, '__version__') and _LooseVersion(libcloud.__version__) < _LooseVersion(REQUIRED_LIBCLOUD_VERSION): raise ImportError() logging.getLogger('libcloud').setLevel(logging.CRITICAL) HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False def __virtual__(): ''' Only load if libcloud libraries exist. ''' if not HAS_LIBCLOUD: msg = ('A apache-libcloud library with version at least {0} was not ' 'found').format(REQUIRED_LIBCLOUD_VERSION) return (False, msg) return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def _get_driver(profile): config = __salt__['config.option']('libcloud_storage')[profile] cls = get_driver(config['driver']) args = config.copy() del args['driver'] args['key'] = config.get('key') args['secret'] = config.get('secret', None) args['secure'] = config.get('secure', True) args['host'] = config.get('host', None) args['port'] = config.get('port', None) return cls(**args) def list_containers(profile, **libcloud_kwargs): ''' Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) containers = conn.list_containers(**libcloud_kwargs) ret = [] for container in containers: ret.append({ 'name': container.name, 'extra': container.extra }) return ret def create_container(container_name, profile, **libcloud_kwargs): ''' Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.create_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container(container_name, profile, **libcloud_kwargs): ''' List container details for the given container_name on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container_object(container_name, object_name, profile, **libcloud_kwargs): ''' Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_container_object(container_name, object_name, **libcloud_kwargs) return { 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data} def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1 ''' conn = _get_driver(profile=profile) obj = conn.get_object(container_name, object_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs) def upload_object(file_path, container_name, object_name, profile, extra=None, verify_hash=True, headers=None, **libcloud_kwargs): ''' Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) obj = conn.upload_object(file_path, container, object_name, extra, verify_hash, headers, **libcloud_kwargs) return obj.name def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_object(container_name, object_name, **libcloud_kwargs) return conn.delete_object(obj) def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) return conn.delete_container(container, **libcloud_kwargs) def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
saltstack/salt
salt/modules/libcloud_storage.py
create_container
python
def create_container(container_name, profile, **libcloud_kwargs): ''' Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.create_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra }
Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L152-L177
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _get_driver(profile):\n config = __salt__['config.option']('libcloud_storage')[profile]\n cls = get_driver(config['driver'])\n args = config.copy()\n del args['driver']\n args['key'] = config.get('key')\n args['secret'] = config.get('secret', None)\n args['secure'] = config.get('secure', True)\n args['host'] = config.get('host', None)\n args['port'] = config.get('port', None)\n return cls(**args)\n" ]
# -*- coding: utf-8 -*- ''' Apache Libcloud Storage Management ================================== Connection module for Apache Libcloud Storage (object/blob) management for a full list of supported clouds, see http://libcloud.readthedocs.io/en/latest/storage/supported_providers.html Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack swift .. versionadded:: 2018.3.0 :configuration: This module uses a configuration profile for one or multiple Storage providers .. code-block:: yaml libcloud_storage: profile_test1: driver: google_storage key: GOOG0123456789ABCXYZ secret: mysecret profile_test2: driver: s3 key: 12345 secret: mysecret :depends: apache-libcloud ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs import salt.utils.args import salt.utils.compat from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) # Import third party libs REQUIRED_LIBCLOUD_VERSION = '1.5.0' try: #pylint: disable=unused-import import libcloud from libcloud.storage.providers import get_driver #pylint: enable=unused-import if hasattr(libcloud, '__version__') and _LooseVersion(libcloud.__version__) < _LooseVersion(REQUIRED_LIBCLOUD_VERSION): raise ImportError() logging.getLogger('libcloud').setLevel(logging.CRITICAL) HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False def __virtual__(): ''' Only load if libcloud libraries exist. ''' if not HAS_LIBCLOUD: msg = ('A apache-libcloud library with version at least {0} was not ' 'found').format(REQUIRED_LIBCLOUD_VERSION) return (False, msg) return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def _get_driver(profile): config = __salt__['config.option']('libcloud_storage')[profile] cls = get_driver(config['driver']) args = config.copy() del args['driver'] args['key'] = config.get('key') args['secret'] = config.get('secret', None) args['secure'] = config.get('secure', True) args['host'] = config.get('host', None) args['port'] = config.get('port', None) return cls(**args) def list_containers(profile, **libcloud_kwargs): ''' Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) containers = conn.list_containers(**libcloud_kwargs) ret = [] for container in containers: ret.append({ 'name': container.name, 'extra': container.extra }) return ret def list_container_objects(container_name, profile, **libcloud_kwargs): ''' List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1 ''' conn = _get_driver(profile=profile) container = conn.get_container(container_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) objects = conn.list_container_objects(container, **libcloud_kwargs) ret = [] for obj in objects: ret.append({ 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data }) return ret def get_container(container_name, profile, **libcloud_kwargs): ''' List container details for the given container_name on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container_object(container_name, object_name, profile, **libcloud_kwargs): ''' Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_container_object(container_name, object_name, **libcloud_kwargs) return { 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data} def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1 ''' conn = _get_driver(profile=profile) obj = conn.get_object(container_name, object_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs) def upload_object(file_path, container_name, object_name, profile, extra=None, verify_hash=True, headers=None, **libcloud_kwargs): ''' Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) obj = conn.upload_object(file_path, container, object_name, extra, verify_hash, headers, **libcloud_kwargs) return obj.name def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_object(container_name, object_name, **libcloud_kwargs) return conn.delete_object(obj) def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) return conn.delete_container(container, **libcloud_kwargs) def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
saltstack/salt
salt/modules/libcloud_storage.py
get_container_object
python
def get_container_object(container_name, object_name, profile, **libcloud_kwargs): ''' Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_container_object(container_name, object_name, **libcloud_kwargs) return { 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data}
Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L208-L239
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _get_driver(profile):\n config = __salt__['config.option']('libcloud_storage')[profile]\n cls = get_driver(config['driver'])\n args = config.copy()\n del args['driver']\n args['key'] = config.get('key')\n args['secret'] = config.get('secret', None)\n args['secure'] = config.get('secure', True)\n args['host'] = config.get('host', None)\n args['port'] = config.get('port', None)\n return cls(**args)\n" ]
# -*- coding: utf-8 -*- ''' Apache Libcloud Storage Management ================================== Connection module for Apache Libcloud Storage (object/blob) management for a full list of supported clouds, see http://libcloud.readthedocs.io/en/latest/storage/supported_providers.html Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack swift .. versionadded:: 2018.3.0 :configuration: This module uses a configuration profile for one or multiple Storage providers .. code-block:: yaml libcloud_storage: profile_test1: driver: google_storage key: GOOG0123456789ABCXYZ secret: mysecret profile_test2: driver: s3 key: 12345 secret: mysecret :depends: apache-libcloud ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs import salt.utils.args import salt.utils.compat from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) # Import third party libs REQUIRED_LIBCLOUD_VERSION = '1.5.0' try: #pylint: disable=unused-import import libcloud from libcloud.storage.providers import get_driver #pylint: enable=unused-import if hasattr(libcloud, '__version__') and _LooseVersion(libcloud.__version__) < _LooseVersion(REQUIRED_LIBCLOUD_VERSION): raise ImportError() logging.getLogger('libcloud').setLevel(logging.CRITICAL) HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False def __virtual__(): ''' Only load if libcloud libraries exist. ''' if not HAS_LIBCLOUD: msg = ('A apache-libcloud library with version at least {0} was not ' 'found').format(REQUIRED_LIBCLOUD_VERSION) return (False, msg) return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def _get_driver(profile): config = __salt__['config.option']('libcloud_storage')[profile] cls = get_driver(config['driver']) args = config.copy() del args['driver'] args['key'] = config.get('key') args['secret'] = config.get('secret', None) args['secure'] = config.get('secure', True) args['host'] = config.get('host', None) args['port'] = config.get('port', None) return cls(**args) def list_containers(profile, **libcloud_kwargs): ''' Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) containers = conn.list_containers(**libcloud_kwargs) ret = [] for container in containers: ret.append({ 'name': container.name, 'extra': container.extra }) return ret def list_container_objects(container_name, profile, **libcloud_kwargs): ''' List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1 ''' conn = _get_driver(profile=profile) container = conn.get_container(container_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) objects = conn.list_container_objects(container, **libcloud_kwargs) ret = [] for obj in objects: ret.append({ 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data }) return ret def create_container(container_name, profile, **libcloud_kwargs): ''' Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.create_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container(container_name, profile, **libcloud_kwargs): ''' List container details for the given container_name on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1 ''' conn = _get_driver(profile=profile) obj = conn.get_object(container_name, object_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs) def upload_object(file_path, container_name, object_name, profile, extra=None, verify_hash=True, headers=None, **libcloud_kwargs): ''' Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) obj = conn.upload_object(file_path, container, object_name, extra, verify_hash, headers, **libcloud_kwargs) return obj.name def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_object(container_name, object_name, **libcloud_kwargs) return conn.delete_object(obj) def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) return conn.delete_container(container, **libcloud_kwargs) def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
saltstack/salt
salt/modules/libcloud_storage.py
download_object
python
def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1 ''' conn = _get_driver(profile=profile) obj = conn.get_object(container_name, object_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs)
Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L242-L286
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _get_driver(profile):\n config = __salt__['config.option']('libcloud_storage')[profile]\n cls = get_driver(config['driver'])\n args = config.copy()\n del args['driver']\n args['key'] = config.get('key')\n args['secret'] = config.get('secret', None)\n args['secure'] = config.get('secure', True)\n args['host'] = config.get('host', None)\n args['port'] = config.get('port', None)\n return cls(**args)\n" ]
# -*- coding: utf-8 -*- ''' Apache Libcloud Storage Management ================================== Connection module for Apache Libcloud Storage (object/blob) management for a full list of supported clouds, see http://libcloud.readthedocs.io/en/latest/storage/supported_providers.html Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack swift .. versionadded:: 2018.3.0 :configuration: This module uses a configuration profile for one or multiple Storage providers .. code-block:: yaml libcloud_storage: profile_test1: driver: google_storage key: GOOG0123456789ABCXYZ secret: mysecret profile_test2: driver: s3 key: 12345 secret: mysecret :depends: apache-libcloud ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs import salt.utils.args import salt.utils.compat from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) # Import third party libs REQUIRED_LIBCLOUD_VERSION = '1.5.0' try: #pylint: disable=unused-import import libcloud from libcloud.storage.providers import get_driver #pylint: enable=unused-import if hasattr(libcloud, '__version__') and _LooseVersion(libcloud.__version__) < _LooseVersion(REQUIRED_LIBCLOUD_VERSION): raise ImportError() logging.getLogger('libcloud').setLevel(logging.CRITICAL) HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False def __virtual__(): ''' Only load if libcloud libraries exist. ''' if not HAS_LIBCLOUD: msg = ('A apache-libcloud library with version at least {0} was not ' 'found').format(REQUIRED_LIBCLOUD_VERSION) return (False, msg) return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def _get_driver(profile): config = __salt__['config.option']('libcloud_storage')[profile] cls = get_driver(config['driver']) args = config.copy() del args['driver'] args['key'] = config.get('key') args['secret'] = config.get('secret', None) args['secure'] = config.get('secure', True) args['host'] = config.get('host', None) args['port'] = config.get('port', None) return cls(**args) def list_containers(profile, **libcloud_kwargs): ''' Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) containers = conn.list_containers(**libcloud_kwargs) ret = [] for container in containers: ret.append({ 'name': container.name, 'extra': container.extra }) return ret def list_container_objects(container_name, profile, **libcloud_kwargs): ''' List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1 ''' conn = _get_driver(profile=profile) container = conn.get_container(container_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) objects = conn.list_container_objects(container, **libcloud_kwargs) ret = [] for obj in objects: ret.append({ 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data }) return ret def create_container(container_name, profile, **libcloud_kwargs): ''' Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.create_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container(container_name, profile, **libcloud_kwargs): ''' List container details for the given container_name on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container_object(container_name, object_name, profile, **libcloud_kwargs): ''' Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_container_object(container_name, object_name, **libcloud_kwargs) return { 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data} def upload_object(file_path, container_name, object_name, profile, extra=None, verify_hash=True, headers=None, **libcloud_kwargs): ''' Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) obj = conn.upload_object(file_path, container, object_name, extra, verify_hash, headers, **libcloud_kwargs) return obj.name def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_object(container_name, object_name, **libcloud_kwargs) return conn.delete_object(obj) def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) return conn.delete_container(container, **libcloud_kwargs) def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
saltstack/salt
salt/modules/libcloud_storage.py
upload_object
python
def upload_object(file_path, container_name, object_name, profile, extra=None, verify_hash=True, headers=None, **libcloud_kwargs): ''' Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) obj = conn.upload_object(file_path, container, object_name, extra, verify_hash, headers, **libcloud_kwargs) return obj.name
Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L289-L334
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _get_driver(profile):\n config = __salt__['config.option']('libcloud_storage')[profile]\n cls = get_driver(config['driver'])\n args = config.copy()\n del args['driver']\n args['key'] = config.get('key')\n args['secret'] = config.get('secret', None)\n args['secure'] = config.get('secure', True)\n args['host'] = config.get('host', None)\n args['port'] = config.get('port', None)\n return cls(**args)\n" ]
# -*- coding: utf-8 -*- ''' Apache Libcloud Storage Management ================================== Connection module for Apache Libcloud Storage (object/blob) management for a full list of supported clouds, see http://libcloud.readthedocs.io/en/latest/storage/supported_providers.html Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack swift .. versionadded:: 2018.3.0 :configuration: This module uses a configuration profile for one or multiple Storage providers .. code-block:: yaml libcloud_storage: profile_test1: driver: google_storage key: GOOG0123456789ABCXYZ secret: mysecret profile_test2: driver: s3 key: 12345 secret: mysecret :depends: apache-libcloud ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs import salt.utils.args import salt.utils.compat from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) # Import third party libs REQUIRED_LIBCLOUD_VERSION = '1.5.0' try: #pylint: disable=unused-import import libcloud from libcloud.storage.providers import get_driver #pylint: enable=unused-import if hasattr(libcloud, '__version__') and _LooseVersion(libcloud.__version__) < _LooseVersion(REQUIRED_LIBCLOUD_VERSION): raise ImportError() logging.getLogger('libcloud').setLevel(logging.CRITICAL) HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False def __virtual__(): ''' Only load if libcloud libraries exist. ''' if not HAS_LIBCLOUD: msg = ('A apache-libcloud library with version at least {0} was not ' 'found').format(REQUIRED_LIBCLOUD_VERSION) return (False, msg) return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def _get_driver(profile): config = __salt__['config.option']('libcloud_storage')[profile] cls = get_driver(config['driver']) args = config.copy() del args['driver'] args['key'] = config.get('key') args['secret'] = config.get('secret', None) args['secure'] = config.get('secure', True) args['host'] = config.get('host', None) args['port'] = config.get('port', None) return cls(**args) def list_containers(profile, **libcloud_kwargs): ''' Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) containers = conn.list_containers(**libcloud_kwargs) ret = [] for container in containers: ret.append({ 'name': container.name, 'extra': container.extra }) return ret def list_container_objects(container_name, profile, **libcloud_kwargs): ''' List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1 ''' conn = _get_driver(profile=profile) container = conn.get_container(container_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) objects = conn.list_container_objects(container, **libcloud_kwargs) ret = [] for obj in objects: ret.append({ 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data }) return ret def create_container(container_name, profile, **libcloud_kwargs): ''' Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.create_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container(container_name, profile, **libcloud_kwargs): ''' List container details for the given container_name on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container_object(container_name, object_name, profile, **libcloud_kwargs): ''' Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_container_object(container_name, object_name, **libcloud_kwargs) return { 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data} def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1 ''' conn = _get_driver(profile=profile) obj = conn.get_object(container_name, object_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs) def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_object(container_name, object_name, **libcloud_kwargs) return conn.delete_object(obj) def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) return conn.delete_container(container, **libcloud_kwargs) def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
saltstack/salt
salt/modules/libcloud_storage.py
delete_object
python
def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_object(container_name, object_name, **libcloud_kwargs) return conn.delete_object(obj)
Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L337-L366
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _get_driver(profile):\n config = __salt__['config.option']('libcloud_storage')[profile]\n cls = get_driver(config['driver'])\n args = config.copy()\n del args['driver']\n args['key'] = config.get('key')\n args['secret'] = config.get('secret', None)\n args['secure'] = config.get('secure', True)\n args['host'] = config.get('host', None)\n args['port'] = config.get('port', None)\n return cls(**args)\n" ]
# -*- coding: utf-8 -*- ''' Apache Libcloud Storage Management ================================== Connection module for Apache Libcloud Storage (object/blob) management for a full list of supported clouds, see http://libcloud.readthedocs.io/en/latest/storage/supported_providers.html Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack swift .. versionadded:: 2018.3.0 :configuration: This module uses a configuration profile for one or multiple Storage providers .. code-block:: yaml libcloud_storage: profile_test1: driver: google_storage key: GOOG0123456789ABCXYZ secret: mysecret profile_test2: driver: s3 key: 12345 secret: mysecret :depends: apache-libcloud ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs import salt.utils.args import salt.utils.compat from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) # Import third party libs REQUIRED_LIBCLOUD_VERSION = '1.5.0' try: #pylint: disable=unused-import import libcloud from libcloud.storage.providers import get_driver #pylint: enable=unused-import if hasattr(libcloud, '__version__') and _LooseVersion(libcloud.__version__) < _LooseVersion(REQUIRED_LIBCLOUD_VERSION): raise ImportError() logging.getLogger('libcloud').setLevel(logging.CRITICAL) HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False def __virtual__(): ''' Only load if libcloud libraries exist. ''' if not HAS_LIBCLOUD: msg = ('A apache-libcloud library with version at least {0} was not ' 'found').format(REQUIRED_LIBCLOUD_VERSION) return (False, msg) return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def _get_driver(profile): config = __salt__['config.option']('libcloud_storage')[profile] cls = get_driver(config['driver']) args = config.copy() del args['driver'] args['key'] = config.get('key') args['secret'] = config.get('secret', None) args['secure'] = config.get('secure', True) args['host'] = config.get('host', None) args['port'] = config.get('port', None) return cls(**args) def list_containers(profile, **libcloud_kwargs): ''' Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) containers = conn.list_containers(**libcloud_kwargs) ret = [] for container in containers: ret.append({ 'name': container.name, 'extra': container.extra }) return ret def list_container_objects(container_name, profile, **libcloud_kwargs): ''' List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1 ''' conn = _get_driver(profile=profile) container = conn.get_container(container_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) objects = conn.list_container_objects(container, **libcloud_kwargs) ret = [] for obj in objects: ret.append({ 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data }) return ret def create_container(container_name, profile, **libcloud_kwargs): ''' Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.create_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container(container_name, profile, **libcloud_kwargs): ''' List container details for the given container_name on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container_object(container_name, object_name, profile, **libcloud_kwargs): ''' Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_container_object(container_name, object_name, **libcloud_kwargs) return { 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data} def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1 ''' conn = _get_driver(profile=profile) obj = conn.get_object(container_name, object_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs) def upload_object(file_path, container_name, object_name, profile, extra=None, verify_hash=True, headers=None, **libcloud_kwargs): ''' Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) obj = conn.upload_object(file_path, container, object_name, extra, verify_hash, headers, **libcloud_kwargs) return obj.name def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) return conn.delete_container(container, **libcloud_kwargs) def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
saltstack/salt
salt/modules/libcloud_storage.py
delete_container
python
def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) return conn.delete_container(container, **libcloud_kwargs)
Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: True if an object container has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_container MyFolder profile1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_storage.py#L369-L395
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _get_driver(profile):\n config = __salt__['config.option']('libcloud_storage')[profile]\n cls = get_driver(config['driver'])\n args = config.copy()\n del args['driver']\n args['key'] = config.get('key')\n args['secret'] = config.get('secret', None)\n args['secure'] = config.get('secure', True)\n args['host'] = config.get('host', None)\n args['port'] = config.get('port', None)\n return cls(**args)\n" ]
# -*- coding: utf-8 -*- ''' Apache Libcloud Storage Management ================================== Connection module for Apache Libcloud Storage (object/blob) management for a full list of supported clouds, see http://libcloud.readthedocs.io/en/latest/storage/supported_providers.html Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack swift .. versionadded:: 2018.3.0 :configuration: This module uses a configuration profile for one or multiple Storage providers .. code-block:: yaml libcloud_storage: profile_test1: driver: google_storage key: GOOG0123456789ABCXYZ secret: mysecret profile_test2: driver: s3 key: 12345 secret: mysecret :depends: apache-libcloud ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs import salt.utils.args import salt.utils.compat from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) # Import third party libs REQUIRED_LIBCLOUD_VERSION = '1.5.0' try: #pylint: disable=unused-import import libcloud from libcloud.storage.providers import get_driver #pylint: enable=unused-import if hasattr(libcloud, '__version__') and _LooseVersion(libcloud.__version__) < _LooseVersion(REQUIRED_LIBCLOUD_VERSION): raise ImportError() logging.getLogger('libcloud').setLevel(logging.CRITICAL) HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False def __virtual__(): ''' Only load if libcloud libraries exist. ''' if not HAS_LIBCLOUD: msg = ('A apache-libcloud library with version at least {0} was not ' 'found').format(REQUIRED_LIBCLOUD_VERSION) return (False, msg) return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def _get_driver(profile): config = __salt__['config.option']('libcloud_storage')[profile] cls = get_driver(config['driver']) args = config.copy() del args['driver'] args['key'] = config.get('key') args['secret'] = config.get('secret', None) args['secure'] = config.get('secure', True) args['host'] = config.get('host', None) args['port'] = config.get('port', None) return cls(**args) def list_containers(profile, **libcloud_kwargs): ''' Return a list of containers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_containers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_containers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) containers = conn.list_containers(**libcloud_kwargs) ret = [] for container in containers: ret.append({ 'name': container.name, 'extra': container.extra }) return ret def list_container_objects(container_name, profile, **libcloud_kwargs): ''' List container objects (e.g. files) for the given container_id on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_container_objects method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_container_objects MyFolder profile1 ''' conn = _get_driver(profile=profile) container = conn.get_container(container_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) objects = conn.list_container_objects(container, **libcloud_kwargs) ret = [] for obj in objects: ret.append({ 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data }) return ret def create_container(container_name, profile, **libcloud_kwargs): ''' Create a container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.create_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container(container_name, profile, **libcloud_kwargs): ''' List container details for the given container_name on the given profile :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container MyFolder profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name, **libcloud_kwargs) return { 'name': container.name, 'extra': container.extra } def get_container_object(container_name, object_name, profile, **libcloud_kwargs): ''' Get the details for a container object (file or object in the cloud) :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_container_object method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_container_object MyFolder MyFile.xyz profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_container_object(container_name, object_name, **libcloud_kwargs) return { 'name': obj.name, 'size': obj.size, 'hash': obj.hash, 'container': obj.container.name, 'extra': obj.extra, 'meta_data': obj.meta_data} def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param destination_path: Full path to a file or a directory where the incoming file will be saved. :type destination_path: ``str`` :param profile: The profile key :type profile: ``str`` :param overwrite_existing: True to overwrite an existing file, defaults to False. :type overwrite_existing: ``bool`` :param delete_on_failure: True to delete a partially downloaded file if the download was not successful (hash mismatch / file size). :type delete_on_failure: ``bool`` :param libcloud_kwargs: Extra arguments for the driver's download_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully downloaded, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1 ''' conn = _get_driver(profile=profile) obj = conn.get_object(container_name, object_name) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs) def upload_object(file_path, container_name, object_name, profile, extra=None, verify_hash=True, headers=None, **libcloud_kwargs): ''' Upload an object currently located on a disk. :param file_path: Path to the object on disk. :type file_path: ``str`` :param container_name: Destination container. :type container_name: ``str`` :param object_name: Object name. :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param verify_hash: Verify hash :type verify_hash: ``bool`` :param extra: Extra attributes (driver specific). (optional) :type extra: ``dict`` :param headers: (optional) Additional request headers, such as CORS headers. For example: headers = {'Access-Control-Allow-Origin': 'http://mozilla.com'} :type headers: ``dict`` :param libcloud_kwargs: Extra arguments for the driver's upload_object method :type libcloud_kwargs: ``dict`` :return: The object name in the cloud :rtype: ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.upload_object /file/to/me.jpg MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) container = conn.get_container(container_name) obj = conn.upload_object(file_path, container, object_name, extra, verify_hash, headers, **libcloud_kwargs) return obj.name def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_object method :type libcloud_kwargs: ``dict`` :return: True if an object has been successfully deleted, False otherwise. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) obj = conn.get_object(container_name, object_name, **libcloud_kwargs) return conn.delete_object(obj) def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
saltstack/salt
salt/utils/vault.py
_get_token_and_url_from_master
python
def _get_token_and_url_from_master(): ''' Get a token with correct policies for the minion, and the url to the Vault service ''' minion_id = __grains__['id'] pki_dir = __opts__['pki_dir'] # When rendering pillars, the module executes on the master, but the token # should be issued for the minion, so that the correct policies are applied if __opts__.get('__role', 'minion') == 'minion': private_key = '{0}/minion.pem'.format(pki_dir) log.debug('Running on minion, signing token request with key %s', private_key) signature = base64.b64encode(salt.crypt.sign_message( private_key, minion_id )) result = __salt__['publish.runner']( 'vault.generate_token', arg=[minion_id, signature] ) else: private_key = '{0}/master.pem'.format(pki_dir) log.debug('Running on master, signing token request for %s with key %s', minion_id, private_key) signature = base64.b64encode(salt.crypt.sign_message( private_key, minion_id )) result = __salt__['saltutil.runner']( 'vault.generate_token', minion_id=minion_id, signature=signature, impersonated_by_master=True ) if not result: log.error('Failed to get token from master! No result returned - ' 'is the peer publish configuration correct?') raise salt.exceptions.CommandExecutionError(result) if not isinstance(result, dict): log.error('Failed to get token from master! ' 'Response is not a dict: %s', result) raise salt.exceptions.CommandExecutionError(result) if 'error' in result: log.error('Failed to get token from master! ' 'An error was returned: %s', result['error']) raise salt.exceptions.CommandExecutionError(result) return { 'url': result['url'], 'token': result['token'], 'verify': result.get('verify', None), }
Get a token with correct policies for the minion, and the url to the Vault service
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vault.py#L39-L92
[ "def sign_message(privkey_path, message, passphrase=None):\n '''\n Use Crypto.Signature.PKCS1_v1_5 to sign a message. Returns the signature.\n '''\n key = get_rsa_key(privkey_path, passphrase)\n log.debug('salt.crypt.sign_message: Signing message.')\n if HAS_M2:\n md = EVP.MessageDigest('sha1')\n md.update(salt.utils.stringutils.to_bytes(message))\n digest = md.final()\n return key.sign(digest)\n else:\n signer = PKCS1_v1_5.new(key)\n return signer.sign(SHA.new(salt.utils.stringutils.to_bytes(message)))\n" ]
# -*- coding: utf-8 -*- ''' :maintainer: SaltStack :maturity: new :platform: all Utilities supporting modules for Hashicorp Vault. Configuration instructions are documented in the execution module docs. ''' from __future__ import absolute_import, print_function, unicode_literals import base64 import logging import requests import salt.crypt import salt.exceptions import salt.utils.versions log = logging.getLogger(__name__) logging.getLogger("requests").setLevel(logging.WARNING) # Load the __salt__ dunder if not already loaded (when called from utils-module) __salt__ = None def __virtual__(): # pylint: disable=expected-2-blank-lines-found-0 try: global __salt__ # pylint: disable=global-statement if not __salt__: __salt__ = salt.loader.minion_mods(__opts__) return True except Exception as e: log.error("Could not load __salt__: %s", e) return False def get_vault_connection(): ''' Get the connection details for calling Vault, from local configuration if it exists, or from the master otherwise ''' def _use_local_config(): log.debug('Using Vault connection details from local config') try: if __opts__['vault']['auth']['method'] == 'approle': verify = __opts__['vault'].get('verify', None) if _selftoken_expired(): log.debug('Vault token expired. Recreating one') # Requesting a short ttl token url = '{0}/v1/auth/approle/login'.format(__opts__['vault']['url']) payload = {'role_id': __opts__['vault']['auth']['role_id']} if 'secret_id' in __opts__['vault']['auth']: payload['secret_id'] = __opts__['vault']['auth']['secret_id'] response = requests.post(url, json=payload, verify=verify) if response.status_code != 200: errmsg = 'An error occured while getting a token from approle' raise salt.exceptions.CommandExecutionError(errmsg) __opts__['vault']['auth']['token'] = response.json()['auth']['client_token'] if __opts__['vault']['auth']['method'] == 'wrapped_token': verify = __opts__['vault'].get('verify', None) if _wrapped_token_valid(): url = '{0}/v1/sys/wrapping/unwrap'.format(__opts__['vault']['url']) headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.post(url, headers=headers, verify=verify) if response.status_code != 200: errmsg = 'An error occured while unwrapping vault token' raise salt.exceptions.CommandExecutionError(errmsg) __opts__['vault']['auth']['token'] = response.json()['auth']['client_token'] return { 'url': __opts__['vault']['url'], 'token': __opts__['vault']['auth']['token'], 'verify': __opts__['vault'].get('verify', None) } except KeyError as err: errmsg = 'Minion has "vault" config section, but could not find key "{0}" within'.format(err.message) raise salt.exceptions.CommandExecutionError(errmsg) if 'vault' in __opts__ and __opts__.get('__role', 'minion') == 'master': if 'id' in __grains__: log.debug('Contacting master for Vault connection details') return _get_token_and_url_from_master() else: return _use_local_config() elif any((__opts__['local'], __opts__['file_client'] == 'local', __opts__['master_type'] == 'disable')): return _use_local_config() else: log.debug('Contacting master for Vault connection details') return _get_token_and_url_from_master() def make_request(method, resource, token=None, vault_url=None, get_token_url=False, **args): ''' Make a request to Vault ''' if not token or not vault_url: connection = get_vault_connection() token, vault_url = connection['token'], connection['url'] if 'verify' not in args: args['verify'] = connection['verify'] url = "{0}/{1}".format(vault_url, resource) headers = {'X-Vault-Token': token, 'Content-Type': 'application/json'} response = requests.request(method, url, headers=headers, **args) if get_token_url: return response, token, vault_url else: return response def _selftoken_expired(): ''' Validate the current token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/auth/token/lookup-self'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return True headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.get(url, headers=headers, verify=verify) if response.status_code != 200: return True return False except Exception as e: raise salt.exceptions.CommandExecutionError( 'Error while looking up self token : {0}'.format(e) ) def _wrapped_token_valid(): ''' Validate the wrapped token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/sys/wrapping/lookup'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return False headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.post(url, headers=headers, verify=verify) if response.status_code != 200: return False return True except Exception as e: raise salt.exceptions.CommandExecutionError( 'Error while looking up wrapped token : {0}'.format(e) )
saltstack/salt
salt/utils/vault.py
get_vault_connection
python
def get_vault_connection(): ''' Get the connection details for calling Vault, from local configuration if it exists, or from the master otherwise ''' def _use_local_config(): log.debug('Using Vault connection details from local config') try: if __opts__['vault']['auth']['method'] == 'approle': verify = __opts__['vault'].get('verify', None) if _selftoken_expired(): log.debug('Vault token expired. Recreating one') # Requesting a short ttl token url = '{0}/v1/auth/approle/login'.format(__opts__['vault']['url']) payload = {'role_id': __opts__['vault']['auth']['role_id']} if 'secret_id' in __opts__['vault']['auth']: payload['secret_id'] = __opts__['vault']['auth']['secret_id'] response = requests.post(url, json=payload, verify=verify) if response.status_code != 200: errmsg = 'An error occured while getting a token from approle' raise salt.exceptions.CommandExecutionError(errmsg) __opts__['vault']['auth']['token'] = response.json()['auth']['client_token'] if __opts__['vault']['auth']['method'] == 'wrapped_token': verify = __opts__['vault'].get('verify', None) if _wrapped_token_valid(): url = '{0}/v1/sys/wrapping/unwrap'.format(__opts__['vault']['url']) headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.post(url, headers=headers, verify=verify) if response.status_code != 200: errmsg = 'An error occured while unwrapping vault token' raise salt.exceptions.CommandExecutionError(errmsg) __opts__['vault']['auth']['token'] = response.json()['auth']['client_token'] return { 'url': __opts__['vault']['url'], 'token': __opts__['vault']['auth']['token'], 'verify': __opts__['vault'].get('verify', None) } except KeyError as err: errmsg = 'Minion has "vault" config section, but could not find key "{0}" within'.format(err.message) raise salt.exceptions.CommandExecutionError(errmsg) if 'vault' in __opts__ and __opts__.get('__role', 'minion') == 'master': if 'id' in __grains__: log.debug('Contacting master for Vault connection details') return _get_token_and_url_from_master() else: return _use_local_config() elif any((__opts__['local'], __opts__['file_client'] == 'local', __opts__['master_type'] == 'disable')): return _use_local_config() else: log.debug('Contacting master for Vault connection details') return _get_token_and_url_from_master()
Get the connection details for calling Vault, from local configuration if it exists, or from the master otherwise
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vault.py#L95-L146
[ "def _get_token_and_url_from_master():\n '''\n Get a token with correct policies for the minion, and the url to the Vault\n service\n '''\n minion_id = __grains__['id']\n pki_dir = __opts__['pki_dir']\n\n # When rendering pillars, the module executes on the master, but the token\n # should be issued for the minion, so that the correct policies are applied\n if __opts__.get('__role', 'minion') == 'minion':\n private_key = '{0}/minion.pem'.format(pki_dir)\n log.debug('Running on minion, signing token request with key %s',\n private_key)\n signature = base64.b64encode(salt.crypt.sign_message(\n private_key,\n minion_id\n ))\n result = __salt__['publish.runner'](\n 'vault.generate_token',\n arg=[minion_id, signature]\n )\n else:\n private_key = '{0}/master.pem'.format(pki_dir)\n log.debug('Running on master, signing token request for %s with key %s',\n minion_id, private_key)\n signature = base64.b64encode(salt.crypt.sign_message(\n private_key,\n minion_id\n ))\n result = __salt__['saltutil.runner'](\n 'vault.generate_token',\n minion_id=minion_id,\n signature=signature,\n impersonated_by_master=True\n )\n\n if not result:\n log.error('Failed to get token from master! No result returned - '\n 'is the peer publish configuration correct?')\n raise salt.exceptions.CommandExecutionError(result)\n if not isinstance(result, dict):\n log.error('Failed to get token from master! '\n 'Response is not a dict: %s', result)\n raise salt.exceptions.CommandExecutionError(result)\n if 'error' in result:\n log.error('Failed to get token from master! '\n 'An error was returned: %s', result['error'])\n raise salt.exceptions.CommandExecutionError(result)\n return {\n 'url': result['url'],\n 'token': result['token'],\n 'verify': result.get('verify', None),\n }\n", "def _use_local_config():\n log.debug('Using Vault connection details from local config')\n try:\n if __opts__['vault']['auth']['method'] == 'approle':\n verify = __opts__['vault'].get('verify', None)\n if _selftoken_expired():\n log.debug('Vault token expired. Recreating one')\n # Requesting a short ttl token\n url = '{0}/v1/auth/approle/login'.format(__opts__['vault']['url'])\n payload = {'role_id': __opts__['vault']['auth']['role_id']}\n if 'secret_id' in __opts__['vault']['auth']:\n payload['secret_id'] = __opts__['vault']['auth']['secret_id']\n response = requests.post(url, json=payload, verify=verify)\n if response.status_code != 200:\n errmsg = 'An error occured while getting a token from approle'\n raise salt.exceptions.CommandExecutionError(errmsg)\n __opts__['vault']['auth']['token'] = response.json()['auth']['client_token']\n if __opts__['vault']['auth']['method'] == 'wrapped_token':\n verify = __opts__['vault'].get('verify', None)\n if _wrapped_token_valid():\n url = '{0}/v1/sys/wrapping/unwrap'.format(__opts__['vault']['url'])\n headers = {'X-Vault-Token': __opts__['vault']['auth']['token']}\n response = requests.post(url, headers=headers, verify=verify)\n if response.status_code != 200:\n errmsg = 'An error occured while unwrapping vault token'\n raise salt.exceptions.CommandExecutionError(errmsg)\n __opts__['vault']['auth']['token'] = response.json()['auth']['client_token']\n return {\n 'url': __opts__['vault']['url'],\n 'token': __opts__['vault']['auth']['token'],\n 'verify': __opts__['vault'].get('verify', None)\n }\n except KeyError as err:\n errmsg = 'Minion has \"vault\" config section, but could not find key \"{0}\" within'.format(err.message)\n raise salt.exceptions.CommandExecutionError(errmsg)\n" ]
# -*- coding: utf-8 -*- ''' :maintainer: SaltStack :maturity: new :platform: all Utilities supporting modules for Hashicorp Vault. Configuration instructions are documented in the execution module docs. ''' from __future__ import absolute_import, print_function, unicode_literals import base64 import logging import requests import salt.crypt import salt.exceptions import salt.utils.versions log = logging.getLogger(__name__) logging.getLogger("requests").setLevel(logging.WARNING) # Load the __salt__ dunder if not already loaded (when called from utils-module) __salt__ = None def __virtual__(): # pylint: disable=expected-2-blank-lines-found-0 try: global __salt__ # pylint: disable=global-statement if not __salt__: __salt__ = salt.loader.minion_mods(__opts__) return True except Exception as e: log.error("Could not load __salt__: %s", e) return False def _get_token_and_url_from_master(): ''' Get a token with correct policies for the minion, and the url to the Vault service ''' minion_id = __grains__['id'] pki_dir = __opts__['pki_dir'] # When rendering pillars, the module executes on the master, but the token # should be issued for the minion, so that the correct policies are applied if __opts__.get('__role', 'minion') == 'minion': private_key = '{0}/minion.pem'.format(pki_dir) log.debug('Running on minion, signing token request with key %s', private_key) signature = base64.b64encode(salt.crypt.sign_message( private_key, minion_id )) result = __salt__['publish.runner']( 'vault.generate_token', arg=[minion_id, signature] ) else: private_key = '{0}/master.pem'.format(pki_dir) log.debug('Running on master, signing token request for %s with key %s', minion_id, private_key) signature = base64.b64encode(salt.crypt.sign_message( private_key, minion_id )) result = __salt__['saltutil.runner']( 'vault.generate_token', minion_id=minion_id, signature=signature, impersonated_by_master=True ) if not result: log.error('Failed to get token from master! No result returned - ' 'is the peer publish configuration correct?') raise salt.exceptions.CommandExecutionError(result) if not isinstance(result, dict): log.error('Failed to get token from master! ' 'Response is not a dict: %s', result) raise salt.exceptions.CommandExecutionError(result) if 'error' in result: log.error('Failed to get token from master! ' 'An error was returned: %s', result['error']) raise salt.exceptions.CommandExecutionError(result) return { 'url': result['url'], 'token': result['token'], 'verify': result.get('verify', None), } def make_request(method, resource, token=None, vault_url=None, get_token_url=False, **args): ''' Make a request to Vault ''' if not token or not vault_url: connection = get_vault_connection() token, vault_url = connection['token'], connection['url'] if 'verify' not in args: args['verify'] = connection['verify'] url = "{0}/{1}".format(vault_url, resource) headers = {'X-Vault-Token': token, 'Content-Type': 'application/json'} response = requests.request(method, url, headers=headers, **args) if get_token_url: return response, token, vault_url else: return response def _selftoken_expired(): ''' Validate the current token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/auth/token/lookup-self'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return True headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.get(url, headers=headers, verify=verify) if response.status_code != 200: return True return False except Exception as e: raise salt.exceptions.CommandExecutionError( 'Error while looking up self token : {0}'.format(e) ) def _wrapped_token_valid(): ''' Validate the wrapped token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/sys/wrapping/lookup'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return False headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.post(url, headers=headers, verify=verify) if response.status_code != 200: return False return True except Exception as e: raise salt.exceptions.CommandExecutionError( 'Error while looking up wrapped token : {0}'.format(e) )
saltstack/salt
salt/utils/vault.py
make_request
python
def make_request(method, resource, token=None, vault_url=None, get_token_url=False, **args): ''' Make a request to Vault ''' if not token or not vault_url: connection = get_vault_connection() token, vault_url = connection['token'], connection['url'] if 'verify' not in args: args['verify'] = connection['verify'] url = "{0}/{1}".format(vault_url, resource) headers = {'X-Vault-Token': token, 'Content-Type': 'application/json'} response = requests.request(method, url, headers=headers, **args) if get_token_url: return response, token, vault_url else: return response
Make a request to Vault
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vault.py#L149-L166
[ "def get_vault_connection():\n '''\n Get the connection details for calling Vault, from local configuration if\n it exists, or from the master otherwise\n '''\n def _use_local_config():\n log.debug('Using Vault connection details from local config')\n try:\n if __opts__['vault']['auth']['method'] == 'approle':\n verify = __opts__['vault'].get('verify', None)\n if _selftoken_expired():\n log.debug('Vault token expired. Recreating one')\n # Requesting a short ttl token\n url = '{0}/v1/auth/approle/login'.format(__opts__['vault']['url'])\n payload = {'role_id': __opts__['vault']['auth']['role_id']}\n if 'secret_id' in __opts__['vault']['auth']:\n payload['secret_id'] = __opts__['vault']['auth']['secret_id']\n response = requests.post(url, json=payload, verify=verify)\n if response.status_code != 200:\n errmsg = 'An error occured while getting a token from approle'\n raise salt.exceptions.CommandExecutionError(errmsg)\n __opts__['vault']['auth']['token'] = response.json()['auth']['client_token']\n if __opts__['vault']['auth']['method'] == 'wrapped_token':\n verify = __opts__['vault'].get('verify', None)\n if _wrapped_token_valid():\n url = '{0}/v1/sys/wrapping/unwrap'.format(__opts__['vault']['url'])\n headers = {'X-Vault-Token': __opts__['vault']['auth']['token']}\n response = requests.post(url, headers=headers, verify=verify)\n if response.status_code != 200:\n errmsg = 'An error occured while unwrapping vault token'\n raise salt.exceptions.CommandExecutionError(errmsg)\n __opts__['vault']['auth']['token'] = response.json()['auth']['client_token']\n return {\n 'url': __opts__['vault']['url'],\n 'token': __opts__['vault']['auth']['token'],\n 'verify': __opts__['vault'].get('verify', None)\n }\n except KeyError as err:\n errmsg = 'Minion has \"vault\" config section, but could not find key \"{0}\" within'.format(err.message)\n raise salt.exceptions.CommandExecutionError(errmsg)\n\n if 'vault' in __opts__ and __opts__.get('__role', 'minion') == 'master':\n if 'id' in __grains__:\n log.debug('Contacting master for Vault connection details')\n return _get_token_and_url_from_master()\n else:\n return _use_local_config()\n elif any((__opts__['local'], __opts__['file_client'] == 'local', __opts__['master_type'] == 'disable')):\n return _use_local_config()\n else:\n log.debug('Contacting master for Vault connection details')\n return _get_token_and_url_from_master()\n" ]
# -*- coding: utf-8 -*- ''' :maintainer: SaltStack :maturity: new :platform: all Utilities supporting modules for Hashicorp Vault. Configuration instructions are documented in the execution module docs. ''' from __future__ import absolute_import, print_function, unicode_literals import base64 import logging import requests import salt.crypt import salt.exceptions import salt.utils.versions log = logging.getLogger(__name__) logging.getLogger("requests").setLevel(logging.WARNING) # Load the __salt__ dunder if not already loaded (when called from utils-module) __salt__ = None def __virtual__(): # pylint: disable=expected-2-blank-lines-found-0 try: global __salt__ # pylint: disable=global-statement if not __salt__: __salt__ = salt.loader.minion_mods(__opts__) return True except Exception as e: log.error("Could not load __salt__: %s", e) return False def _get_token_and_url_from_master(): ''' Get a token with correct policies for the minion, and the url to the Vault service ''' minion_id = __grains__['id'] pki_dir = __opts__['pki_dir'] # When rendering pillars, the module executes on the master, but the token # should be issued for the minion, so that the correct policies are applied if __opts__.get('__role', 'minion') == 'minion': private_key = '{0}/minion.pem'.format(pki_dir) log.debug('Running on minion, signing token request with key %s', private_key) signature = base64.b64encode(salt.crypt.sign_message( private_key, minion_id )) result = __salt__['publish.runner']( 'vault.generate_token', arg=[minion_id, signature] ) else: private_key = '{0}/master.pem'.format(pki_dir) log.debug('Running on master, signing token request for %s with key %s', minion_id, private_key) signature = base64.b64encode(salt.crypt.sign_message( private_key, minion_id )) result = __salt__['saltutil.runner']( 'vault.generate_token', minion_id=minion_id, signature=signature, impersonated_by_master=True ) if not result: log.error('Failed to get token from master! No result returned - ' 'is the peer publish configuration correct?') raise salt.exceptions.CommandExecutionError(result) if not isinstance(result, dict): log.error('Failed to get token from master! ' 'Response is not a dict: %s', result) raise salt.exceptions.CommandExecutionError(result) if 'error' in result: log.error('Failed to get token from master! ' 'An error was returned: %s', result['error']) raise salt.exceptions.CommandExecutionError(result) return { 'url': result['url'], 'token': result['token'], 'verify': result.get('verify', None), } def get_vault_connection(): ''' Get the connection details for calling Vault, from local configuration if it exists, or from the master otherwise ''' def _use_local_config(): log.debug('Using Vault connection details from local config') try: if __opts__['vault']['auth']['method'] == 'approle': verify = __opts__['vault'].get('verify', None) if _selftoken_expired(): log.debug('Vault token expired. Recreating one') # Requesting a short ttl token url = '{0}/v1/auth/approle/login'.format(__opts__['vault']['url']) payload = {'role_id': __opts__['vault']['auth']['role_id']} if 'secret_id' in __opts__['vault']['auth']: payload['secret_id'] = __opts__['vault']['auth']['secret_id'] response = requests.post(url, json=payload, verify=verify) if response.status_code != 200: errmsg = 'An error occured while getting a token from approle' raise salt.exceptions.CommandExecutionError(errmsg) __opts__['vault']['auth']['token'] = response.json()['auth']['client_token'] if __opts__['vault']['auth']['method'] == 'wrapped_token': verify = __opts__['vault'].get('verify', None) if _wrapped_token_valid(): url = '{0}/v1/sys/wrapping/unwrap'.format(__opts__['vault']['url']) headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.post(url, headers=headers, verify=verify) if response.status_code != 200: errmsg = 'An error occured while unwrapping vault token' raise salt.exceptions.CommandExecutionError(errmsg) __opts__['vault']['auth']['token'] = response.json()['auth']['client_token'] return { 'url': __opts__['vault']['url'], 'token': __opts__['vault']['auth']['token'], 'verify': __opts__['vault'].get('verify', None) } except KeyError as err: errmsg = 'Minion has "vault" config section, but could not find key "{0}" within'.format(err.message) raise salt.exceptions.CommandExecutionError(errmsg) if 'vault' in __opts__ and __opts__.get('__role', 'minion') == 'master': if 'id' in __grains__: log.debug('Contacting master for Vault connection details') return _get_token_and_url_from_master() else: return _use_local_config() elif any((__opts__['local'], __opts__['file_client'] == 'local', __opts__['master_type'] == 'disable')): return _use_local_config() else: log.debug('Contacting master for Vault connection details') return _get_token_and_url_from_master() def _selftoken_expired(): ''' Validate the current token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/auth/token/lookup-self'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return True headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.get(url, headers=headers, verify=verify) if response.status_code != 200: return True return False except Exception as e: raise salt.exceptions.CommandExecutionError( 'Error while looking up self token : {0}'.format(e) ) def _wrapped_token_valid(): ''' Validate the wrapped token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/sys/wrapping/lookup'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return False headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.post(url, headers=headers, verify=verify) if response.status_code != 200: return False return True except Exception as e: raise salt.exceptions.CommandExecutionError( 'Error while looking up wrapped token : {0}'.format(e) )
saltstack/salt
salt/states/status.py
loadavg
python
def loadavg(name, maximum=None, minimum=None): ''' Return the current load average for the specified minion. Available values for name are `1-min`, `5-min` and `15-min`. `minimum` and `maximum` values should be passed in as strings. ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state data = __salt__['status.loadavg']() if name not in data: ret['result'] = False ret['comment'] += 'Requested load average {0} not available '.format( name ) return ret if minimum and maximum and minimum >= maximum: ret['comment'] += 'Min must be less than max' if ret['comment']: return ret cap = float(data[name]) ret['data'] = data[name] if minimum: if cap < float(minimum): ret['comment'] = 'Load avg is below minimum of {0} at {1}'.format( minimum, cap) return ret if maximum: if cap > float(maximum): ret['comment'] = 'Load avg above maximum of {0} at {1}'.format( maximum, cap) return ret ret['comment'] = 'Load avg in acceptable range' ret['result'] = True return ret
Return the current load average for the specified minion. Available values for name are `1-min`, `5-min` and `15-min`. `minimum` and `maximum` values should be passed in as strings.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/status.py#L15-L53
null
# -*- coding: utf-8 -*- ''' Minion status monitoring Maps to the `status` execution module. ''' from __future__ import absolute_import, print_function, unicode_literals __monitor__ = [ 'loadavg', 'process', ] def process(name): ''' Return whether the specified signature is found in the process tree. This differs slightly from the services states, in that it may refer to a process that is not managed via the init system. ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state data = __salt__['status.pid'](name) if not data: ret['result'] = False ret['comment'] += 'Process signature "{0}" not found '.format( name ) return ret ret['data'] = data ret['comment'] += 'Process signature "{0}" was found '.format( name ) ret['result'] = True return ret
saltstack/salt
salt/states/status.py
process
python
def process(name): ''' Return whether the specified signature is found in the process tree. This differs slightly from the services states, in that it may refer to a process that is not managed via the init system. ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state data = __salt__['status.pid'](name) if not data: ret['result'] = False ret['comment'] += 'Process signature "{0}" not found '.format( name ) return ret ret['data'] = data ret['comment'] += 'Process signature "{0}" was found '.format( name ) ret['result'] = True return ret
Return whether the specified signature is found in the process tree. This differs slightly from the services states, in that it may refer to a process that is not managed via the init system.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/status.py#L56-L81
null
# -*- coding: utf-8 -*- ''' Minion status monitoring Maps to the `status` execution module. ''' from __future__ import absolute_import, print_function, unicode_literals __monitor__ = [ 'loadavg', 'process', ] def loadavg(name, maximum=None, minimum=None): ''' Return the current load average for the specified minion. Available values for name are `1-min`, `5-min` and `15-min`. `minimum` and `maximum` values should be passed in as strings. ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state data = __salt__['status.loadavg']() if name not in data: ret['result'] = False ret['comment'] += 'Requested load average {0} not available '.format( name ) return ret if minimum and maximum and minimum >= maximum: ret['comment'] += 'Min must be less than max' if ret['comment']: return ret cap = float(data[name]) ret['data'] = data[name] if minimum: if cap < float(minimum): ret['comment'] = 'Load avg is below minimum of {0} at {1}'.format( minimum, cap) return ret if maximum: if cap > float(maximum): ret['comment'] = 'Load avg above maximum of {0} at {1}'.format( maximum, cap) return ret ret['comment'] = 'Load avg in acceptable range' ret['result'] = True return ret
saltstack/salt
salt/states/blockdev.py
tuned
python
def tuned(name, **kwargs): ''' Manage options of block device name The name of the block device opts: - read-ahead Read-ahead buffer size - filesystem-read-ahead Filesystem Read-ahead buffer size - read-only Set Read-Only - read-write Set Read-Write ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} kwarg_map = {'read-ahead': 'getra', 'filesystem-read-ahead': 'getfra', 'read-only': 'getro', 'read-write': 'getro'} if not __salt__['file.is_blkdev']: ret['comment'] = ('Changes to {0} cannot be applied. ' 'Not a block device. ').format(name) elif __opts__['test']: ret['comment'] = 'Changes to {0} will be applied '.format(name) ret['result'] = None return ret else: current = __salt__['disk.dump'](name) changes = __salt__['disk.tune'](name, **kwargs) changeset = {} for key in kwargs: if key in kwarg_map: switch = kwarg_map[key] if current[switch] != changes[switch]: if isinstance(kwargs[key], bool): old = (current[switch] == '1') new = (changes[switch] == '1') else: old = current[switch] new = changes[switch] if key == 'read-write': old = not old new = not new changeset[key] = 'Changed from {0} to {1}'.format(old, new) if changes: if changeset: ret['comment'] = ('Block device {0} ' 'successfully modified ').format(name) ret['changes'] = changeset else: ret['comment'] = 'Block device {0} already in correct state'.format(name) else: ret['comment'] = 'Failed to modify block device {0}'.format(name) ret['result'] = False return ret
Manage options of block device name The name of the block device opts: - read-ahead Read-ahead buffer size - filesystem-read-ahead Filesystem Read-ahead buffer size - read-only Set Read-Only - read-write Set Read-Write
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/blockdev.py#L51-L117
null
# -*- coding: utf-8 -*- ''' Management of Block Devices A state module to manage blockdevices .. code-block:: yaml /dev/sda: blockdev.tuned: - read-only: True master-data: blockdev.tuned: - name: /dev/vg/master-data - read-only: True - read-ahead: 1024 .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import os.path import time import logging # Import salt libs import salt.utils.path from salt.ext.six.moves import range __virtualname__ = 'blockdev' # Init logger log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if the disk execution module is available ''' if 'disk.tune' in __salt__: return __virtualname__ return (False, ('Cannot load the {0} state module: ' 'disk execution module not found'.format(__virtualname__))) def formatted(name, fs_type='ext4', force=False, **kwargs): ''' Manage filesystems of partitions. name The name of the block device fs_type The filesystem it should be formatted as force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. .. versionadded:: 2016.11.0 ''' ret = {'changes': {}, 'comment': '{0} already formatted with {1}'.format(name, fs_type), 'name': name, 'result': False} if not os.path.exists(name): ret['comment'] = '{0} does not exist'.format(name) return ret current_fs = _checkblk(name) if current_fs == fs_type: ret['result'] = True return ret elif not salt.utils.path.which('mkfs.{0}'.format(fs_type)): ret['comment'] = 'Invalid fs_type: {0}'.format(fs_type) ret['result'] = False return ret elif __opts__['test']: ret['comment'] = 'Changes to {0} will be applied '.format(name) ret['result'] = None return ret __salt__['disk.format'](name, fs_type, force=force, **kwargs) # Repeat fstype check up to 10 times with 3s sleeping between each # to avoid detection failing although mkfs has succeeded # see https://github.com/saltstack/salt/issues/25775 # This retry maybe superfluous - switching to blkid for i in range(10): log.info('Check blk fstype attempt %d of 10', i + 1) current_fs = _checkblk(name) if current_fs == fs_type: ret['comment'] = ('{0} has been formatted ' 'with {1}').format(name, fs_type) ret['changes'] = {'new': fs_type, 'old': current_fs} ret['result'] = True return ret if current_fs == '': log.info('Waiting 3s before next check') time.sleep(3) else: break ret['comment'] = 'Failed to format {0}'.format(name) ret['result'] = False return ret def _checkblk(name): ''' Check if the blk exists and return its fstype if ok ''' blk = __salt__['cmd.run']('blkid -o value -s TYPE {0}'.format(name), ignore_retcode=True) return '' if not blk else blk
saltstack/salt
salt/states/blockdev.py
formatted
python
def formatted(name, fs_type='ext4', force=False, **kwargs): ''' Manage filesystems of partitions. name The name of the block device fs_type The filesystem it should be formatted as force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. .. versionadded:: 2016.11.0 ''' ret = {'changes': {}, 'comment': '{0} already formatted with {1}'.format(name, fs_type), 'name': name, 'result': False} if not os.path.exists(name): ret['comment'] = '{0} does not exist'.format(name) return ret current_fs = _checkblk(name) if current_fs == fs_type: ret['result'] = True return ret elif not salt.utils.path.which('mkfs.{0}'.format(fs_type)): ret['comment'] = 'Invalid fs_type: {0}'.format(fs_type) ret['result'] = False return ret elif __opts__['test']: ret['comment'] = 'Changes to {0} will be applied '.format(name) ret['result'] = None return ret __salt__['disk.format'](name, fs_type, force=force, **kwargs) # Repeat fstype check up to 10 times with 3s sleeping between each # to avoid detection failing although mkfs has succeeded # see https://github.com/saltstack/salt/issues/25775 # This retry maybe superfluous - switching to blkid for i in range(10): log.info('Check blk fstype attempt %d of 10', i + 1) current_fs = _checkblk(name) if current_fs == fs_type: ret['comment'] = ('{0} has been formatted ' 'with {1}').format(name, fs_type) ret['changes'] = {'new': fs_type, 'old': current_fs} ret['result'] = True return ret if current_fs == '': log.info('Waiting 3s before next check') time.sleep(3) else: break ret['comment'] = 'Failed to format {0}'.format(name) ret['result'] = False return ret
Manage filesystems of partitions. name The name of the block device fs_type The filesystem it should be formatted as force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/blockdev.py#L120-L188
[ "def _checkblk(name):\n '''\n Check if the blk exists and return its fstype if ok\n '''\n\n blk = __salt__['cmd.run']('blkid -o value -s TYPE {0}'.format(name),\n ignore_retcode=True)\n return '' if not blk else blk\n" ]
# -*- coding: utf-8 -*- ''' Management of Block Devices A state module to manage blockdevices .. code-block:: yaml /dev/sda: blockdev.tuned: - read-only: True master-data: blockdev.tuned: - name: /dev/vg/master-data - read-only: True - read-ahead: 1024 .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import os.path import time import logging # Import salt libs import salt.utils.path from salt.ext.six.moves import range __virtualname__ = 'blockdev' # Init logger log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if the disk execution module is available ''' if 'disk.tune' in __salt__: return __virtualname__ return (False, ('Cannot load the {0} state module: ' 'disk execution module not found'.format(__virtualname__))) def tuned(name, **kwargs): ''' Manage options of block device name The name of the block device opts: - read-ahead Read-ahead buffer size - filesystem-read-ahead Filesystem Read-ahead buffer size - read-only Set Read-Only - read-write Set Read-Write ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} kwarg_map = {'read-ahead': 'getra', 'filesystem-read-ahead': 'getfra', 'read-only': 'getro', 'read-write': 'getro'} if not __salt__['file.is_blkdev']: ret['comment'] = ('Changes to {0} cannot be applied. ' 'Not a block device. ').format(name) elif __opts__['test']: ret['comment'] = 'Changes to {0} will be applied '.format(name) ret['result'] = None return ret else: current = __salt__['disk.dump'](name) changes = __salt__['disk.tune'](name, **kwargs) changeset = {} for key in kwargs: if key in kwarg_map: switch = kwarg_map[key] if current[switch] != changes[switch]: if isinstance(kwargs[key], bool): old = (current[switch] == '1') new = (changes[switch] == '1') else: old = current[switch] new = changes[switch] if key == 'read-write': old = not old new = not new changeset[key] = 'Changed from {0} to {1}'.format(old, new) if changes: if changeset: ret['comment'] = ('Block device {0} ' 'successfully modified ').format(name) ret['changes'] = changeset else: ret['comment'] = 'Block device {0} already in correct state'.format(name) else: ret['comment'] = 'Failed to modify block device {0}'.format(name) ret['result'] = False return ret def _checkblk(name): ''' Check if the blk exists and return its fstype if ok ''' blk = __salt__['cmd.run']('blkid -o value -s TYPE {0}'.format(name), ignore_retcode=True) return '' if not blk else blk
saltstack/salt
salt/states/blockdev.py
_checkblk
python
def _checkblk(name): ''' Check if the blk exists and return its fstype if ok ''' blk = __salt__['cmd.run']('blkid -o value -s TYPE {0}'.format(name), ignore_retcode=True) return '' if not blk else blk
Check if the blk exists and return its fstype if ok
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/blockdev.py#L191-L198
null
# -*- coding: utf-8 -*- ''' Management of Block Devices A state module to manage blockdevices .. code-block:: yaml /dev/sda: blockdev.tuned: - read-only: True master-data: blockdev.tuned: - name: /dev/vg/master-data - read-only: True - read-ahead: 1024 .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import os.path import time import logging # Import salt libs import salt.utils.path from salt.ext.six.moves import range __virtualname__ = 'blockdev' # Init logger log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if the disk execution module is available ''' if 'disk.tune' in __salt__: return __virtualname__ return (False, ('Cannot load the {0} state module: ' 'disk execution module not found'.format(__virtualname__))) def tuned(name, **kwargs): ''' Manage options of block device name The name of the block device opts: - read-ahead Read-ahead buffer size - filesystem-read-ahead Filesystem Read-ahead buffer size - read-only Set Read-Only - read-write Set Read-Write ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} kwarg_map = {'read-ahead': 'getra', 'filesystem-read-ahead': 'getfra', 'read-only': 'getro', 'read-write': 'getro'} if not __salt__['file.is_blkdev']: ret['comment'] = ('Changes to {0} cannot be applied. ' 'Not a block device. ').format(name) elif __opts__['test']: ret['comment'] = 'Changes to {0} will be applied '.format(name) ret['result'] = None return ret else: current = __salt__['disk.dump'](name) changes = __salt__['disk.tune'](name, **kwargs) changeset = {} for key in kwargs: if key in kwarg_map: switch = kwarg_map[key] if current[switch] != changes[switch]: if isinstance(kwargs[key], bool): old = (current[switch] == '1') new = (changes[switch] == '1') else: old = current[switch] new = changes[switch] if key == 'read-write': old = not old new = not new changeset[key] = 'Changed from {0} to {1}'.format(old, new) if changes: if changeset: ret['comment'] = ('Block device {0} ' 'successfully modified ').format(name) ret['changes'] = changeset else: ret['comment'] = 'Block device {0} already in correct state'.format(name) else: ret['comment'] = 'Failed to modify block device {0}'.format(name) ret['result'] = False return ret def formatted(name, fs_type='ext4', force=False, **kwargs): ''' Manage filesystems of partitions. name The name of the block device fs_type The filesystem it should be formatted as force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. .. versionadded:: 2016.11.0 ''' ret = {'changes': {}, 'comment': '{0} already formatted with {1}'.format(name, fs_type), 'name': name, 'result': False} if not os.path.exists(name): ret['comment'] = '{0} does not exist'.format(name) return ret current_fs = _checkblk(name) if current_fs == fs_type: ret['result'] = True return ret elif not salt.utils.path.which('mkfs.{0}'.format(fs_type)): ret['comment'] = 'Invalid fs_type: {0}'.format(fs_type) ret['result'] = False return ret elif __opts__['test']: ret['comment'] = 'Changes to {0} will be applied '.format(name) ret['result'] = None return ret __salt__['disk.format'](name, fs_type, force=force, **kwargs) # Repeat fstype check up to 10 times with 3s sleeping between each # to avoid detection failing although mkfs has succeeded # see https://github.com/saltstack/salt/issues/25775 # This retry maybe superfluous - switching to blkid for i in range(10): log.info('Check blk fstype attempt %d of 10', i + 1) current_fs = _checkblk(name) if current_fs == fs_type: ret['comment'] = ('{0} has been formatted ' 'with {1}').format(name, fs_type) ret['changes'] = {'new': fs_type, 'old': current_fs} ret['result'] = True return ret if current_fs == '': log.info('Waiting 3s before next check') time.sleep(3) else: break ret['comment'] = 'Failed to format {0}'.format(name) ret['result'] = False return ret
saltstack/salt
salt/modules/napalm_snmp.py
remove_config
python
def remove_config(chassis_id=None, community=None, contact=None, location=None, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Removes a configuration element from the SNMP configuration. :param chassis_id: (optional) Chassis ID :param community: (optional) A dictionary having the following optional keys: - acl (if any policy / ACL need to be set) - mode: rw or ro. Default: ro :param contact: Contact details :param location: Location :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: A dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied CLI Example: .. code-block:: bash salt '*' snmp.remove_config community='abcd' ''' dic = { 'template_name': 'delete_snmp_config', 'test': test, 'commit': commit } if chassis_id: dic['chassis_id'] = chassis_id if community: dic['community'] = community if contact: dic['contact'] = contact if location: dic['location'] = location dic['inherit_napalm_device'] = napalm_device # pylint: disable=undefined-variable return __salt__['net.load_template'](**dic)
Removes a configuration element from the SNMP configuration. :param chassis_id: (optional) Chassis ID :param community: (optional) A dictionary having the following optional keys: - acl (if any policy / ACL need to be set) - mode: rw or ro. Default: ro :param contact: Contact details :param location: Location :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: A dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied CLI Example: .. code-block:: bash salt '*' snmp.remove_config community='abcd'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_snmp.py#L84-L149
null
# -*- coding: utf-8 -*- ''' NAPALM SNMP =========== Manages SNMP on network devices. :codeauthor: Mircea Ulinic <mircea@cloudflare.com> :maturity: new :depends: napalm :platform: unix Dependencies ------------ - :mod:`NAPALM proxy minion <salt.proxy.napalm>` - :mod:`NET basic features <salt.modules.napalm_network>` .. seealso:: :mod:`SNMP configuration management state <salt.states.netsnmp>` .. versionadded:: 2016.11.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging log = logging.getLogger(__file__) # import NAPALM utils import salt.utils.napalm from salt.utils.napalm import proxy_napalm_wrap # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'snmp' __proxyenabled__ = ['napalm'] # uses NAPALM-based proxy to interact with network devices __virtual_aliases__ = ('napalm_snmp',) # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' NAPALM library must be installed for this module to work and run in a (proxy) minion. ''' return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__) # ---------------------------------------------------------------------------------------------------------------------- # helper functions -- will not be exported # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- @proxy_napalm_wrap def config(**kwargs): # pylint: disable=unused-argument ''' Returns the SNMP configuration CLI Example: .. code-block:: bash salt '*' snmp.config ''' return salt.utils.napalm.call( napalm_device, # pylint: disable=undefined-variable 'get_snmp_information', **{ } ) @proxy_napalm_wrap @proxy_napalm_wrap def update_config(chassis_id=None, community=None, contact=None, location=None, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Updates the SNMP configuration. :param chassis_id: (optional) Chassis ID :param community: (optional) A dictionary having the following optional keys: - acl (if any policy / ACL need to be set) - mode: rw or ro. Default: ro :param contact: Contact details :param location: Location :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return a dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied CLI Example: .. code-block:: bash salt 'edge01.lon01' snmp.update_config location="Greenwich, UK" test=True Output example (for the CLI example above): .. code-block:: yaml edge01.lon01: ---------- already_configured: False comment: Configuration discarded. diff: [edit snmp] - location "London, UK"; + location "Greenwich, UK"; result: True ''' dic = { 'template_name': 'snmp_config', 'test': test, 'commit': commit } if chassis_id: dic['chassis_id'] = chassis_id if community: dic['community'] = community if contact: dic['contact'] = contact if location: dic['location'] = location dic['inherit_napalm_device'] = napalm_device # pylint: disable=undefined-variable return __salt__['net.load_template'](**dic)
saltstack/salt
salt/modules/nacl.py
keygen
python
def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs)
Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L166-L187
[ "def keygen(sk_file=None, pk_file=None, **kwargs):\n '''\n Use libnacl to generate a keypair.\n\n If no `sk_file` is defined return a keypair.\n\n If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`.\n\n When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated\n using the `sk_file`.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call nacl.keygen\n salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl\n salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub\n salt-call --local nacl.keygen\n '''\n if 'keyfile' in kwargs:\n salt.utils.versions.warn_until(\n 'Neon',\n 'The \\'keyfile\\' argument has been deprecated and will be removed in Salt '\n '{version}. Please use \\'sk_file\\' argument instead.'\n )\n sk_file = kwargs['keyfile']\n\n if sk_file is None:\n kp = libnacl.public.SecretKey()\n return {'sk': base64.b64encode(kp.sk), 'pk': base64.b64encode(kp.pk)}\n\n if pk_file is None:\n pk_file = '{0}.pub'.format(sk_file)\n\n if sk_file and pk_file is None:\n if not os.path.isfile(sk_file):\n kp = libnacl.public.SecretKey()\n with salt.utils.files.fopen(sk_file, 'wb') as keyf:\n keyf.write(base64.b64encode(kp.sk))\n if salt.utils.platform.is_windows():\n cur_user = salt.utils.win_functions.get_current_user()\n salt.utils.win_dacl.set_owner(sk_file, cur_user)\n salt.utils.win_dacl.set_permissions(sk_file, cur_user, 'full_control', 'grant', reset_perms=True, protected=True)\n else:\n # chmod 0600 file\n os.chmod(sk_file, 1536)\n return 'saved sk_file: {0}'.format(sk_file)\n else:\n raise Exception('sk_file:{0} already exist.'.format(sk_file))\n\n if sk_file is None and pk_file:\n raise Exception('sk_file: Must be set inorder to generate a public key.')\n\n if os.path.isfile(sk_file) and os.path.isfile(pk_file):\n raise Exception('sk_file:{0} and pk_file:{1} already exist.'.format(sk_file, pk_file))\n\n if os.path.isfile(sk_file) and not os.path.isfile(pk_file):\n # generate pk using the sk\n with salt.utils.files.fopen(sk_file, 'rb') as keyf:\n sk = salt.utils.stringutils.to_unicode(keyf.read()).rstrip('\\n')\n sk = base64.b64decode(sk)\n kp = libnacl.public.SecretKey(sk)\n with salt.utils.files.fopen(pk_file, 'wb') as keyf:\n keyf.write(base64.b64encode(kp.pk))\n return 'saved pk_file: {0}'.format(pk_file)\n\n kp = libnacl.public.SecretKey()\n with salt.utils.files.fopen(sk_file, 'wb') as keyf:\n keyf.write(base64.b64encode(kp.sk))\n if salt.utils.platform.is_windows():\n cur_user = salt.utils.win_functions.get_current_user()\n salt.utils.win_dacl.set_owner(sk_file, cur_user)\n salt.utils.win_dacl.set_permissions(sk_file, cur_user, 'full_control', 'grant', reset_perms=True, protected=True)\n else:\n # chmod 0600 file\n os.chmod(sk_file, 1536)\n with salt.utils.files.fopen(pk_file, 'wb') as keyf:\n keyf.write(base64.b64encode(kp.pk))\n return 'saved sk_file:{0} pk_file: {1}'.format(sk_file, pk_file)\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs) def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs) def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs) def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs) def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs) def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs) def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs) def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
saltstack/salt
salt/modules/nacl.py
enc
python
def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs)
Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L190-L197
[ "def enc(data, **kwargs):\n '''\n Alias to `{box_type}_encrypt`\n\n box_type: secretbox, sealedbox(default)\n '''\n if 'keyfile' in kwargs:\n salt.utils.versions.warn_until(\n 'Neon',\n 'The \\'keyfile\\' argument has been deprecated and will be removed in Salt '\n '{version}. Please use \\'sk_file\\' argument instead.'\n )\n kwargs['sk_file'] = kwargs['keyfile']\n\n if 'key' in kwargs:\n salt.utils.versions.warn_until(\n 'Neon',\n 'The \\'key\\' argument has been deprecated and will be removed in Salt '\n '{version}. Please use \\'sk\\' argument instead.'\n )\n kwargs['sk'] = kwargs['key']\n\n box_type = _get_config(**kwargs)['box_type']\n if box_type == 'secretbox':\n return secretbox_encrypt(data, **kwargs)\n return sealedbox_encrypt(data, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs) def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs) def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs) def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs) def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs) def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs) def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs) def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
saltstack/salt
salt/modules/nacl.py
enc_file
python
def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs)
This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L200-L218
[ "def enc_file(name, out=None, **kwargs):\n '''\n This is a helper function to encrypt a file and return its contents.\n\n You can provide an optional output file using `out`\n\n `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-run nacl.enc_file name=/tmp/id_rsa\n salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert\n salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \\\n sk_file=/etc/salt/pki/master/nacl.pub\n '''\n try:\n data = __salt__['cp.get_file_str'](name)\n except Exception as e:\n # likly using salt-run so fallback to local filesystem\n with salt.utils.files.fopen(name, 'rb') as f:\n data = salt.utils.stringutils.to_unicode(f.read())\n d = enc(data, **kwargs)\n if out:\n if os.path.isfile(out):\n raise Exception('file:{0} already exist.'.format(out))\n with salt.utils.files.fopen(out, 'wb') as f:\n f.write(salt.utils.stringutils.to_bytes(d))\n return 'Wrote: {0}'.format(out)\n return d\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs) def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs) def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs) def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs) def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs) def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs) def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs) def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
saltstack/salt
salt/modules/nacl.py
dec
python
def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs)
Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L221-L228
[ "def dec(data, **kwargs):\n '''\n Alias to `{box_type}_decrypt`\n\n box_type: secretbox, sealedbox(default)\n '''\n if 'keyfile' in kwargs:\n salt.utils.versions.warn_until(\n 'Neon',\n 'The \\'keyfile\\' argument has been deprecated and will be removed in Salt '\n '{version}. Please use \\'sk_file\\' argument instead.'\n )\n kwargs['sk_file'] = kwargs['keyfile']\n\n # set boxtype to `secretbox` to maintain backward compatibility\n kwargs['box_type'] = 'secretbox'\n\n if 'key' in kwargs:\n salt.utils.versions.warn_until(\n 'Neon',\n 'The \\'key\\' argument has been deprecated and will be removed in Salt '\n '{version}. Please use \\'sk\\' argument instead.'\n )\n kwargs['sk'] = kwargs['key']\n\n # set boxtype to `secretbox` to maintain backward compatibility\n kwargs['box_type'] = 'secretbox'\n\n box_type = _get_config(**kwargs)['box_type']\n if box_type == 'secretbox':\n return secretbox_decrypt(data, **kwargs)\n return sealedbox_decrypt(data, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs) def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs) def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs) def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs) def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs) def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs) def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs) def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
saltstack/salt
salt/modules/nacl.py
dec_file
python
def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs)
This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L231-L249
[ "def dec_file(name, out=None, **kwargs):\n '''\n This is a helper function to decrypt a file and return its contents.\n\n You can provide an optional output file using `out`\n\n `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-run nacl.dec_file name=/tmp/id_rsa.nacl\n salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa\n salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \\\n sk_file=/etc/salt/pki/master/nacl.pub\n '''\n try:\n data = __salt__['cp.get_file_str'](name)\n except Exception as e:\n # likly using salt-run so fallback to local filesystem\n with salt.utils.files.fopen(name, 'rb') as f:\n data = salt.utils.stringutils.to_unicode(f.read())\n d = dec(data, **kwargs)\n if out:\n if os.path.isfile(out):\n raise Exception('file:{0} already exist.'.format(out))\n with salt.utils.files.fopen(out, 'wb') as f:\n f.write(salt.utils.stringutils.to_bytes(d))\n return 'Wrote: {0}'.format(out)\n return d\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs) def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs) def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs) def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs) def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs) def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs) def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs) def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
saltstack/salt
salt/modules/nacl.py
sealedbox_encrypt
python
def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs)
Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ='
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L252-L266
[ "def sealedbox_encrypt(data, **kwargs):\n '''\n Encrypt data using a public key generated from `nacl.keygen`.\n The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-run nacl.sealedbox_encrypt datatoenc\n salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub\n salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ='\n '''\n # ensure data is in bytes\n data = salt.utils.stringutils.to_bytes(data)\n\n pk = _get_pk(**kwargs)\n b = libnacl.sealed.SealedBox(pk)\n return base64.b64encode(b.encrypt(data))\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs) def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs) def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs) def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs) def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs) def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs) def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs) def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
saltstack/salt
salt/modules/nacl.py
sealedbox_decrypt
python
def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs)
Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L269-L282
[ "def sealedbox_decrypt(data, **kwargs):\n '''\n Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A=\n salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl\n salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='\n '''\n if data is None:\n return None\n\n # ensure data is in bytes\n data = salt.utils.stringutils.to_bytes(data)\n\n sk = _get_sk(**kwargs)\n keypair = libnacl.public.SecretKey(sk)\n b = libnacl.sealed.SealedBox(keypair)\n return b.decrypt(base64.b64decode(data))\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs) def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs) def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs) def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs) def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs) def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs) def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs) def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
saltstack/salt
salt/modules/nacl.py
secretbox_encrypt
python
def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs)
Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo='
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L285-L299
[ "def secretbox_encrypt(data, **kwargs):\n '''\n Encrypt data using a secret key generated from `nacl.keygen`.\n The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-run nacl.secretbox_encrypt datatoenc\n salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl\n salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo='\n '''\n # ensure data is in bytes\n data = salt.utils.stringutils.to_bytes(data)\n\n sk = _get_sk(**kwargs)\n b = libnacl.secret.SecretBox(sk)\n return base64.b64encode(b.encrypt(data))\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs) def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs) def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs) def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs) def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs) def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs) def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs) def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
saltstack/salt
salt/modules/nacl.py
secretbox_decrypt
python
def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_decrypt(data, **kwargs)
Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nacl.py#L302-L316
[ "def secretbox_decrypt(data, **kwargs):\n '''\n Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key\n that was generated from `nacl.keygen`.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A=\n salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl\n salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='\n '''\n if data is None:\n return None\n\n # ensure data is in bytes\n data = salt.utils.stringutils.to_bytes(data)\n\n key = _get_sk(**kwargs)\n b = libnacl.secret.SecretBox(key=key)\n\n return b.decrypt(base64.b64decode(data))\n" ]
# -*- coding: utf-8 -*- ''' This module helps include encrypted passwords in pillars, grains and salt state files. :depends: libnacl, https://github.com/saltstack/libnacl This is often useful if you wish to store your pillars in source control or share your pillar data with others that you trust. I don't advise making your pillars public regardless if they are encrypted or not. When generating keys and encrypting passwords use --local when using salt-call for extra security. Also consider using just the salt runner nacl when encrypting pillar passwords. :configuration: The following configuration defaults can be define (pillar or config files) Avoid storing private keys in pillars! Ensure master does not have `pillar_opts=True`: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: # NOTE: `key` and `key_file` have been renamed to `sk`, `sk_file` # also `box_type` default changed from secretbox to sealedbox. box_type: sealedbox (default) sk_file: /etc/salt/pki/master/nacl (default) pk_file: /etc/salt/pki/master/nacl.pub (default) sk: None pk: None Usage can override the config defaults: .. code-block:: bash salt-call nacl.enc sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple. To generate your `sk_file` and `pk_file` use: .. code-block:: bash salt-call --local nacl.keygen sk_file=/etc/salt/pki/master/nacl # or if you want to work without files. salt-call --local nacl.keygen local: ---------- pk: /kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= sk: SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow= Now with your keypair, you can encrypt data: You have two option, `sealedbox` or `secretbox`. SecretBox is data encrypted using private key `pk`. Sealedbox is encrypted using public key `pk`. Recommend using Sealedbox because the one way encryption permits developers to encrypt data for source control but not decrypt. Sealedbox only has one key that is for both encryption and decryption. .. code-block:: bash salt-call --local nacl.enc asecretpass pk=/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0= tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58= To decrypt the data: .. code-block:: bash salt-call --local nacl.dec data='tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' \ sk='SVWut5SqNpuPeNzb1b9y6b2eXg2PLIog43GBzp48Sow=' When the keys are defined in the master config you can use them from the nacl runner without extra parameters: .. code-block:: python # cat /etc/salt/master.d/nacl.conf nacl.config: sk_file: /etc/salt/pki/master/nacl pk: 'cTIqXwnUiD1ulg4kXsbeCE7/NoeKEzd4nLeYcCFpd9k=' .. code-block:: bash salt-run nacl.enc 'asecretpass' salt-run nacl.dec 'tqXzeIJnTAM9Xf0mdLcpEdklMbfBGPj2oTKmlgrm3S1DTVVHNnh9h8mU1GKllGq/+cYsk6m5WhGdk58=' .. code-block:: yaml # a salt developers minion could have pillar data that includes a nacl public key nacl.config: pk: '/kfGX7PbWeu099702PBbKWLpG/9p06IQRswkdWHCDk0=' The developer can then use a less-secure system to encrypt data. .. code-block:: bash salt-call --local nacl.enc apassword Pillar files can include protected data that the salt master decrypts: .. code-block:: jinja pillarexample: user: root password1: {{salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hlbWj0llUA+uaVyvou3vJ4=')|json}} cert_key: {{salt.nacl.dec_file('/srv/salt/certs/example.com/key.nacl')|json}} cert_key2: {{salt.nacl.dec_file('salt:///certs/example.com/key.nacl')|json}} Larger files like certificates can be encrypted with: .. code-block:: bash salt-call nacl.enc_file /tmp/cert.crt out=/tmp/cert.nacl # or more advanced cert=$(cat /tmp/cert.crt) salt-call --out=newline_values_only nacl.enc_pub data="$cert" > /tmp/cert.nacl In pillars rended with jinja be sure to include `|json` so line breaks are encoded: .. code-block:: jinja cert: "{{salt.nacl.dec('S2uogToXkgENz9...085KYt')|json}}" In states rendered with jinja it is also good pratice to include `|json`: .. code-block:: jinja {{sls}} private key: file.managed: - name: /etc/ssl/private/cert.key - mode: 700 - contents: "{{pillar['pillarexample']['cert_key']|json}}" Optional small program to encrypt data without needing salt modules. .. code-block:: python #!/bin/python3 import sys, base64, libnacl.sealed pk = base64.b64decode('YOURPUBKEY') b = libnacl.sealed.SealedBox(pk) data = sys.stdin.buffer.read() print(base64.b64encode(b.encrypt(data)).decode()) .. code-block:: bash echo 'apassword' | nacl_enc.py ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.nacl __virtualname__ = 'nacl' def __virtual__(): return salt.utils.nacl.check_requirements() def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples: .. code-block:: bash salt-call nacl.keygen salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.keygen ''' kwargs['opts'] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs) def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc(data, **kwargs) def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.enc_file name=/tmp/id_rsa salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.enc_file(name, out, **kwargs) def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs) def dec_file(name, out=None, **kwargs): ''' This is a helper function to decrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-block:: bash salt-run nacl.dec_file name=/tmp/id_rsa.nacl salt-call nacl.dec_file name=salt://crt/mycert.nacl out=/tmp/id_rsa salt-run nacl.dec_file name=/tmp/id_rsa.nacl box_type=secretbox \ sk_file=/etc/salt/pki/master/nacl.pub ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec_file(name, out, **kwargs) def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_encrypt(data, **kwargs) def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.sealedbox_decrypt(data, **kwargs) def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' ''' kwargs['opts'] = __opts__ return salt.utils.nacl.secretbox_encrypt(data, **kwargs)
saltstack/salt
salt/modules/panos.py
_get_job_results
python
def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response
Executes a query that requires a job for completion. This function will wait for the job to complete and return the results.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L60-L79
[ "def get_job(jid=None):\n '''\n List all a single job by ID.\n\n jid\n The ID of the job to retrieve.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.get_job jid=15\n\n '''\n if not jid:\n raise CommandExecutionError(\"ID option must not be none.\")\n\n query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)}\n\n return __proxy__['panos.call'](query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
deactivate_license
python
def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query)
Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L162-L187
null
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
download_software_file
python
def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query)
Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L230-L262
[ "def _get_job_results(query=None):\n '''\n Executes a query that requires a job for completion. This function will wait for the job to complete\n and return the results.\n '''\n if not query:\n raise CommandExecutionError(\"Query parameters cannot be empty.\")\n\n response = __proxy__['panos.call'](query)\n\n # If the response contains a job, we will wait for the results\n if 'result' in response and 'job' in response['result']:\n jid = response['result']['job']\n\n while get_job(jid)['result']['job']['status'] != 'FIN':\n time.sleep(5)\n\n return get_job(jid)\n else:\n return response\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
download_software_version
python
def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query)
Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L265-L297
[ "def _get_job_results(query=None):\n '''\n Executes a query that requires a job for completion. This function will wait for the job to complete\n and return the results.\n '''\n if not query:\n raise CommandExecutionError(\"Query parameters cannot be empty.\")\n\n response = __proxy__['panos.call'](query)\n\n # If the response contains a job, we will wait for the results\n if 'result' in response and 'job' in response['result']:\n jid = response['result']['job']\n\n while get_job(jid)['result']['job']['status'] != 'FIN':\n time.sleep(5)\n\n return get_job(jid)\n else:\n return response\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
get_jobs
python
def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query)
List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L724-L750
null
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
get_local_admins
python
def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response
Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L865-L888
[ "def get_users_config():\n '''\n Get the local administrative user account configuration.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.get_users_config\n\n '''\n query = {'type': 'config',\n 'action': 'get',\n 'xpath': '/config/mgt-config/users'}\n\n return __proxy__['panos.call'](query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)