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/pagerduty_escalation_policy.py
_diff
python
def _diff(state_data, resource_object): '''helper method to compare salt state info with the PagerDuty API json structure, and determine if we need to update. returns the dict to pass to the PD API to perform the update, or empty dict if no update. ''' objects_differ = None for k, v in state_data.items(): if k == 'escalation_rules': v = _escalation_rules_to_string(v) resource_value = _escalation_rules_to_string(resource_object[k]) else: if k not in resource_object.keys(): objects_differ = True else: resource_value = resource_object[k] if v != resource_value: objects_differ = '{0} {1} {2}'.format(k, v, resource_value) break if objects_differ: return state_data else: return {}
helper method to compare salt state info with the PagerDuty API json structure, and determine if we need to update. returns the dict to pass to the PD API to perform the update, or empty dict if no update.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_escalation_policy.py#L127-L151
null
# -*- coding: utf-8 -*- ''' Manage PagerDuty escalation policies. Schedules and users can be referenced by pagerduty ID, or by name, or by email address. For example: .. code-block:: yaml ensure test escalation policy: pagerduty_escalation_policy.present: - name: bruce test escalation policy - escalation_rules: - targets: - type: schedule id: 'bruce test schedule level1' - type: user id: 'Bruce Sherrod' escalation_delay_in_minutes: 15 - targets: - type: schedule id: 'bruce test schedule level2' escalation_delay_in_minutes: 15 - targets: - type: user id: 'Bruce TestUser1' - type: user id: 'Bruce TestUser2' - type: user id: 'Bruce TestUser3' - type: user id: 'bruce+test4@lyft.com' escalation_delay_in_minutes: 15 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the pygerduty module is available in __salt__ ''' return 'pagerduty_escalation_policy' if 'pagerduty_util.get_resource' in __salt__ else False def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure that a pagerduty escalation policy exists. Will create or update as needed. This method accepts as args everything defined in https://developer.pagerduty.com/documentation/rest/escalation_policies/create. In addition, user and schedule id's will be translated from name (or email address) into PagerDuty unique ids. For example: .. code-block:: yaml pagerduty_escalation_policy.present: - name: bruce test escalation policy - escalation_rules: - targets: - type: schedule id: 'bruce test schedule level1' - type: user id: 'Bruce Sherrod' In this example, 'Bruce Sherrod' will be looked up and replaced with the PagerDuty id (usually a 7 digit all-caps string, e.g. PX6GQL7) ''' # for convenience, we accept id, name, or email for users # and we accept the id or name for schedules for escalation_rule in kwargs['escalation_rules']: for target in escalation_rule['targets']: target_id = None if target['type'] == 'user': user = __salt__['pagerduty_util.get_resource']('users', target['id'], ['email', 'name', 'id'], profile=profile, subdomain=subdomain, api_key=api_key) if user: target_id = user['id'] elif target['type'] == 'schedule': schedule = __salt__['pagerduty_util.get_resource']('schedules', target['id'], ['name', 'id'], profile=profile, subdomain=subdomain, api_key=api_key) if schedule: target_id = schedule['schedule']['id'] if target_id is None: raise Exception('unidentified target: {0}'.format(target)) target['id'] = target_id r = __salt__['pagerduty_util.resource_present']('escalation_policies', ['name', 'id'], _diff, profile, subdomain, api_key, **kwargs) return r def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure that a PagerDuty escalation policy does not exist. Accepts all the arguments that pagerduty_escalation_policy.present accepts; but ignores all arguments except the name. Name can be the escalation policy id or the escalation policy name. ''' r = __salt__['pagerduty_util.resource_absent']('escalation_policies', ['name', 'id'], profile, subdomain, api_key, **kwargs) return r def _escalation_rules_to_string(escalation_rules): 'convert escalation_rules dict to a string for comparison' result = '' for rule in escalation_rules: result += 'escalation_delay_in_minutes: {0} '.format(rule['escalation_delay_in_minutes']) for target in rule['targets']: result += '{0}:{1} '.format(target['type'], target['id']) return result
saltstack/salt
salt/states/pagerduty_escalation_policy.py
_escalation_rules_to_string
python
def _escalation_rules_to_string(escalation_rules): 'convert escalation_rules dict to a string for comparison' result = '' for rule in escalation_rules: result += 'escalation_delay_in_minutes: {0} '.format(rule['escalation_delay_in_minutes']) for target in rule['targets']: result += '{0}:{1} '.format(target['type'], target['id']) return result
convert escalation_rules dict to a string for comparison
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_escalation_policy.py#L154-L161
null
# -*- coding: utf-8 -*- ''' Manage PagerDuty escalation policies. Schedules and users can be referenced by pagerduty ID, or by name, or by email address. For example: .. code-block:: yaml ensure test escalation policy: pagerduty_escalation_policy.present: - name: bruce test escalation policy - escalation_rules: - targets: - type: schedule id: 'bruce test schedule level1' - type: user id: 'Bruce Sherrod' escalation_delay_in_minutes: 15 - targets: - type: schedule id: 'bruce test schedule level2' escalation_delay_in_minutes: 15 - targets: - type: user id: 'Bruce TestUser1' - type: user id: 'Bruce TestUser2' - type: user id: 'Bruce TestUser3' - type: user id: 'bruce+test4@lyft.com' escalation_delay_in_minutes: 15 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the pygerduty module is available in __salt__ ''' return 'pagerduty_escalation_policy' if 'pagerduty_util.get_resource' in __salt__ else False def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure that a pagerduty escalation policy exists. Will create or update as needed. This method accepts as args everything defined in https://developer.pagerduty.com/documentation/rest/escalation_policies/create. In addition, user and schedule id's will be translated from name (or email address) into PagerDuty unique ids. For example: .. code-block:: yaml pagerduty_escalation_policy.present: - name: bruce test escalation policy - escalation_rules: - targets: - type: schedule id: 'bruce test schedule level1' - type: user id: 'Bruce Sherrod' In this example, 'Bruce Sherrod' will be looked up and replaced with the PagerDuty id (usually a 7 digit all-caps string, e.g. PX6GQL7) ''' # for convenience, we accept id, name, or email for users # and we accept the id or name for schedules for escalation_rule in kwargs['escalation_rules']: for target in escalation_rule['targets']: target_id = None if target['type'] == 'user': user = __salt__['pagerduty_util.get_resource']('users', target['id'], ['email', 'name', 'id'], profile=profile, subdomain=subdomain, api_key=api_key) if user: target_id = user['id'] elif target['type'] == 'schedule': schedule = __salt__['pagerduty_util.get_resource']('schedules', target['id'], ['name', 'id'], profile=profile, subdomain=subdomain, api_key=api_key) if schedule: target_id = schedule['schedule']['id'] if target_id is None: raise Exception('unidentified target: {0}'.format(target)) target['id'] = target_id r = __salt__['pagerduty_util.resource_present']('escalation_policies', ['name', 'id'], _diff, profile, subdomain, api_key, **kwargs) return r def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure that a PagerDuty escalation policy does not exist. Accepts all the arguments that pagerduty_escalation_policy.present accepts; but ignores all arguments except the name. Name can be the escalation policy id or the escalation policy name. ''' r = __salt__['pagerduty_util.resource_absent']('escalation_policies', ['name', 'id'], profile, subdomain, api_key, **kwargs) return r def _diff(state_data, resource_object): '''helper method to compare salt state info with the PagerDuty API json structure, and determine if we need to update. returns the dict to pass to the PD API to perform the update, or empty dict if no update. ''' objects_differ = None for k, v in state_data.items(): if k == 'escalation_rules': v = _escalation_rules_to_string(v) resource_value = _escalation_rules_to_string(resource_object[k]) else: if k not in resource_object.keys(): objects_differ = True else: resource_value = resource_object[k] if v != resource_value: objects_differ = '{0} {1} {2}'.format(k, v, resource_value) break if objects_differ: return state_data else: return {}
saltstack/salt
salt/states/rabbitmq_user.py
_check_perms_changes
python
def _check_perms_changes(name, newperms, runas=None, existing=None): ''' Check whether Rabbitmq user's permissions need to be changed. ''' if not newperms: return False if existing is None: try: existing = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: log.error('Error: %s', err) return False perm_need_change = False for vhost_perms in newperms: for vhost, perms in six.iteritems(vhost_perms): if vhost in existing: existing_vhost = existing[vhost] if perms != existing_vhost: # This checks for setting permissions to nothing in the state, # when previous state runs have already set permissions to # nothing. We don't want to report a change in this case. if existing_vhost == '' and perms == ['', '', '']: continue perm_need_change = True else: perm_need_change = True return perm_need_change
Check whether Rabbitmq user's permissions need to be changed.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_user.py#L44-L73
null
# -*- coding: utf-8 -*- ''' Manage RabbitMQ Users ===================== Example: .. code-block:: yaml rabbit_user: rabbitmq_user.present: - password: password - force: True - tags: - monitoring - user - perms: - '/': - '.*' - '.*' - '.*' - runas: rabbitmq ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.path from salt.ext import six from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) def __virtual__(): ''' Only load if RabbitMQ is installed. ''' return salt.utils.path.which('rabbitmqctl') is not None def _get_current_tags(name, runas=None): ''' Whether Rabbitmq user's tags need to be changed ''' try: return list(__salt__['rabbitmq.list_users'](runas=runas)[name]) except CommandExecutionError as err: log.error('Error: %s', err) return [] def present(name, password=None, force=False, tags=None, perms=(), runas=None): ''' Ensure the RabbitMQ user exists. name User name password User's password, if one needs to be set force If user exists, forcibly change the password tags Optional list of tags for the user perms A list of dicts with vhost keys and 3-tuple values runas Name of the user to run the command ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} try: user = __salt__['rabbitmq.user_exists'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret passwd_reqs_update = False if user and password is not None: try: if not __salt__['rabbitmq.check_password'](name, password, runas=runas): passwd_reqs_update = True log.debug('RabbitMQ user %s password update required', name) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if user and not any((force, perms, tags, passwd_reqs_update)): log.debug(('RabbitMQ user \'%s\' exists, password is up to' ' date and force is not set.'), name) ret['comment'] = 'User \'{0}\' is already present.'.format(name) ret['result'] = True return ret if not user: ret['changes'].update({'user': {'old': '', 'new': name}}) if __opts__['test']: ret['result'] = None ret['comment'] = 'User \'{0}\' is set to be created.'.format(name) return ret log.debug( 'RabbitMQ user \'%s\' doesn\'t exist - Creating.', name) try: __salt__['rabbitmq.add_user'](name, password, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret else: log.debug('RabbitMQ user \'%s\' exists', name) if force or passwd_reqs_update: if password is not None: if not __opts__['test']: try: __salt__['rabbitmq.change_password'](name, password, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'password': {'old': '', 'new': 'Set password.'}}) else: if not __opts__['test']: log.debug('Password for %s is not set - Clearing password.', name) try: __salt__['rabbitmq.clear_password'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'password': {'old': 'Removed password.', 'new': ''}}) if tags is not None: current_tags = _get_current_tags(name, runas=runas) if isinstance(tags, six.string_types): tags = tags.split() # Diff the tags sets. Symmetric difference operator ^ will give us # any element in one set, but not both if set(tags) ^ set(current_tags): if not __opts__['test']: try: __salt__['rabbitmq.set_user_tags'](name, tags, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'tags': {'old': current_tags, 'new': tags}}) try: existing_perms = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if _check_perms_changes(name, perms, runas=runas, existing=existing_perms): for vhost_perm in perms: for vhost, perm in six.iteritems(vhost_perm): if not __opts__['test']: try: __salt__['rabbitmq.set_permissions']( vhost, name, perm[0], perm[1], perm[2], runas=runas ) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret new_perms = {vhost: perm} if existing_perms != new_perms: if ret['changes'].get('perms') is None: ret['changes'].update({'perms': {'old': {}, 'new': {}}}) ret['changes']['perms']['old'].update(existing_perms) ret['changes']['perms']['new'].update(new_perms) ret['result'] = True if ret['changes'] == {}: ret['comment'] = '\'{0}\' is already in the desired state.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Configuration for \'{0}\' will change.'.format(name) return ret ret['comment'] = '\'{0}\' was configured.'.format(name) return ret def absent(name, runas=None): ''' Ensure the named user is absent name The name of the user to remove runas User to run the command ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} try: user_exists = __salt__['rabbitmq.user_exists'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if user_exists: if not __opts__['test']: try: __salt__['rabbitmq.delete_user'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'name': {'old': name, 'new': ''}}) else: ret['result'] = True ret['comment'] = 'The user \'{0}\' is not present.'.format(name) return ret if __opts__['test'] and ret['changes']: ret['result'] = None ret['comment'] = 'The user \'{0}\' will be removed.'.format(name) return ret ret['result'] = True ret['comment'] = 'The user \'{0}\' was removed.'.format(name) return ret
saltstack/salt
salt/states/rabbitmq_user.py
_get_current_tags
python
def _get_current_tags(name, runas=None): ''' Whether Rabbitmq user's tags need to be changed ''' try: return list(__salt__['rabbitmq.list_users'](runas=runas)[name]) except CommandExecutionError as err: log.error('Error: %s', err) return []
Whether Rabbitmq user's tags need to be changed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_user.py#L76-L84
null
# -*- coding: utf-8 -*- ''' Manage RabbitMQ Users ===================== Example: .. code-block:: yaml rabbit_user: rabbitmq_user.present: - password: password - force: True - tags: - monitoring - user - perms: - '/': - '.*' - '.*' - '.*' - runas: rabbitmq ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.path from salt.ext import six from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) def __virtual__(): ''' Only load if RabbitMQ is installed. ''' return salt.utils.path.which('rabbitmqctl') is not None def _check_perms_changes(name, newperms, runas=None, existing=None): ''' Check whether Rabbitmq user's permissions need to be changed. ''' if not newperms: return False if existing is None: try: existing = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: log.error('Error: %s', err) return False perm_need_change = False for vhost_perms in newperms: for vhost, perms in six.iteritems(vhost_perms): if vhost in existing: existing_vhost = existing[vhost] if perms != existing_vhost: # This checks for setting permissions to nothing in the state, # when previous state runs have already set permissions to # nothing. We don't want to report a change in this case. if existing_vhost == '' and perms == ['', '', '']: continue perm_need_change = True else: perm_need_change = True return perm_need_change def present(name, password=None, force=False, tags=None, perms=(), runas=None): ''' Ensure the RabbitMQ user exists. name User name password User's password, if one needs to be set force If user exists, forcibly change the password tags Optional list of tags for the user perms A list of dicts with vhost keys and 3-tuple values runas Name of the user to run the command ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} try: user = __salt__['rabbitmq.user_exists'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret passwd_reqs_update = False if user and password is not None: try: if not __salt__['rabbitmq.check_password'](name, password, runas=runas): passwd_reqs_update = True log.debug('RabbitMQ user %s password update required', name) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if user and not any((force, perms, tags, passwd_reqs_update)): log.debug(('RabbitMQ user \'%s\' exists, password is up to' ' date and force is not set.'), name) ret['comment'] = 'User \'{0}\' is already present.'.format(name) ret['result'] = True return ret if not user: ret['changes'].update({'user': {'old': '', 'new': name}}) if __opts__['test']: ret['result'] = None ret['comment'] = 'User \'{0}\' is set to be created.'.format(name) return ret log.debug( 'RabbitMQ user \'%s\' doesn\'t exist - Creating.', name) try: __salt__['rabbitmq.add_user'](name, password, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret else: log.debug('RabbitMQ user \'%s\' exists', name) if force or passwd_reqs_update: if password is not None: if not __opts__['test']: try: __salt__['rabbitmq.change_password'](name, password, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'password': {'old': '', 'new': 'Set password.'}}) else: if not __opts__['test']: log.debug('Password for %s is not set - Clearing password.', name) try: __salt__['rabbitmq.clear_password'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'password': {'old': 'Removed password.', 'new': ''}}) if tags is not None: current_tags = _get_current_tags(name, runas=runas) if isinstance(tags, six.string_types): tags = tags.split() # Diff the tags sets. Symmetric difference operator ^ will give us # any element in one set, but not both if set(tags) ^ set(current_tags): if not __opts__['test']: try: __salt__['rabbitmq.set_user_tags'](name, tags, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'tags': {'old': current_tags, 'new': tags}}) try: existing_perms = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if _check_perms_changes(name, perms, runas=runas, existing=existing_perms): for vhost_perm in perms: for vhost, perm in six.iteritems(vhost_perm): if not __opts__['test']: try: __salt__['rabbitmq.set_permissions']( vhost, name, perm[0], perm[1], perm[2], runas=runas ) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret new_perms = {vhost: perm} if existing_perms != new_perms: if ret['changes'].get('perms') is None: ret['changes'].update({'perms': {'old': {}, 'new': {}}}) ret['changes']['perms']['old'].update(existing_perms) ret['changes']['perms']['new'].update(new_perms) ret['result'] = True if ret['changes'] == {}: ret['comment'] = '\'{0}\' is already in the desired state.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Configuration for \'{0}\' will change.'.format(name) return ret ret['comment'] = '\'{0}\' was configured.'.format(name) return ret def absent(name, runas=None): ''' Ensure the named user is absent name The name of the user to remove runas User to run the command ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} try: user_exists = __salt__['rabbitmq.user_exists'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if user_exists: if not __opts__['test']: try: __salt__['rabbitmq.delete_user'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'name': {'old': name, 'new': ''}}) else: ret['result'] = True ret['comment'] = 'The user \'{0}\' is not present.'.format(name) return ret if __opts__['test'] and ret['changes']: ret['result'] = None ret['comment'] = 'The user \'{0}\' will be removed.'.format(name) return ret ret['result'] = True ret['comment'] = 'The user \'{0}\' was removed.'.format(name) return ret
saltstack/salt
salt/states/rabbitmq_user.py
present
python
def present(name, password=None, force=False, tags=None, perms=(), runas=None): ''' Ensure the RabbitMQ user exists. name User name password User's password, if one needs to be set force If user exists, forcibly change the password tags Optional list of tags for the user perms A list of dicts with vhost keys and 3-tuple values runas Name of the user to run the command ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} try: user = __salt__['rabbitmq.user_exists'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret passwd_reqs_update = False if user and password is not None: try: if not __salt__['rabbitmq.check_password'](name, password, runas=runas): passwd_reqs_update = True log.debug('RabbitMQ user %s password update required', name) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if user and not any((force, perms, tags, passwd_reqs_update)): log.debug(('RabbitMQ user \'%s\' exists, password is up to' ' date and force is not set.'), name) ret['comment'] = 'User \'{0}\' is already present.'.format(name) ret['result'] = True return ret if not user: ret['changes'].update({'user': {'old': '', 'new': name}}) if __opts__['test']: ret['result'] = None ret['comment'] = 'User \'{0}\' is set to be created.'.format(name) return ret log.debug( 'RabbitMQ user \'%s\' doesn\'t exist - Creating.', name) try: __salt__['rabbitmq.add_user'](name, password, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret else: log.debug('RabbitMQ user \'%s\' exists', name) if force or passwd_reqs_update: if password is not None: if not __opts__['test']: try: __salt__['rabbitmq.change_password'](name, password, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'password': {'old': '', 'new': 'Set password.'}}) else: if not __opts__['test']: log.debug('Password for %s is not set - Clearing password.', name) try: __salt__['rabbitmq.clear_password'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'password': {'old': 'Removed password.', 'new': ''}}) if tags is not None: current_tags = _get_current_tags(name, runas=runas) if isinstance(tags, six.string_types): tags = tags.split() # Diff the tags sets. Symmetric difference operator ^ will give us # any element in one set, but not both if set(tags) ^ set(current_tags): if not __opts__['test']: try: __salt__['rabbitmq.set_user_tags'](name, tags, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'tags': {'old': current_tags, 'new': tags}}) try: existing_perms = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if _check_perms_changes(name, perms, runas=runas, existing=existing_perms): for vhost_perm in perms: for vhost, perm in six.iteritems(vhost_perm): if not __opts__['test']: try: __salt__['rabbitmq.set_permissions']( vhost, name, perm[0], perm[1], perm[2], runas=runas ) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret new_perms = {vhost: perm} if existing_perms != new_perms: if ret['changes'].get('perms') is None: ret['changes'].update({'perms': {'old': {}, 'new': {}}}) ret['changes']['perms']['old'].update(existing_perms) ret['changes']['perms']['new'].update(new_perms) ret['result'] = True if ret['changes'] == {}: ret['comment'] = '\'{0}\' is already in the desired state.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Configuration for \'{0}\' will change.'.format(name) return ret ret['comment'] = '\'{0}\' was configured.'.format(name) return ret
Ensure the RabbitMQ user exists. name User name password User's password, if one needs to be set force If user exists, forcibly change the password tags Optional list of tags for the user perms A list of dicts with vhost keys and 3-tuple values runas Name of the user to run the command
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_user.py#L87-L229
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _check_perms_changes(name, newperms, runas=None, existing=None):\n '''\n Check whether Rabbitmq user's permissions need to be changed.\n '''\n if not newperms:\n return False\n\n if existing is None:\n try:\n existing = __salt__['rabbitmq.list_user_permissions'](name, runas=runas)\n except CommandExecutionError as err:\n log.error('Error: %s', err)\n return False\n\n perm_need_change = False\n for vhost_perms in newperms:\n for vhost, perms in six.iteritems(vhost_perms):\n if vhost in existing:\n existing_vhost = existing[vhost]\n if perms != existing_vhost:\n # This checks for setting permissions to nothing in the state,\n # when previous state runs have already set permissions to\n # nothing. We don't want to report a change in this case.\n if existing_vhost == '' and perms == ['', '', '']:\n continue\n perm_need_change = True\n else:\n perm_need_change = True\n\n return perm_need_change\n", "def _get_current_tags(name, runas=None):\n '''\n Whether Rabbitmq user's tags need to be changed\n '''\n try:\n return list(__salt__['rabbitmq.list_users'](runas=runas)[name])\n except CommandExecutionError as err:\n log.error('Error: %s', err)\n return []\n" ]
# -*- coding: utf-8 -*- ''' Manage RabbitMQ Users ===================== Example: .. code-block:: yaml rabbit_user: rabbitmq_user.present: - password: password - force: True - tags: - monitoring - user - perms: - '/': - '.*' - '.*' - '.*' - runas: rabbitmq ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.path from salt.ext import six from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) def __virtual__(): ''' Only load if RabbitMQ is installed. ''' return salt.utils.path.which('rabbitmqctl') is not None def _check_perms_changes(name, newperms, runas=None, existing=None): ''' Check whether Rabbitmq user's permissions need to be changed. ''' if not newperms: return False if existing is None: try: existing = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: log.error('Error: %s', err) return False perm_need_change = False for vhost_perms in newperms: for vhost, perms in six.iteritems(vhost_perms): if vhost in existing: existing_vhost = existing[vhost] if perms != existing_vhost: # This checks for setting permissions to nothing in the state, # when previous state runs have already set permissions to # nothing. We don't want to report a change in this case. if existing_vhost == '' and perms == ['', '', '']: continue perm_need_change = True else: perm_need_change = True return perm_need_change def _get_current_tags(name, runas=None): ''' Whether Rabbitmq user's tags need to be changed ''' try: return list(__salt__['rabbitmq.list_users'](runas=runas)[name]) except CommandExecutionError as err: log.error('Error: %s', err) return [] def absent(name, runas=None): ''' Ensure the named user is absent name The name of the user to remove runas User to run the command ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} try: user_exists = __salt__['rabbitmq.user_exists'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if user_exists: if not __opts__['test']: try: __salt__['rabbitmq.delete_user'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'name': {'old': name, 'new': ''}}) else: ret['result'] = True ret['comment'] = 'The user \'{0}\' is not present.'.format(name) return ret if __opts__['test'] and ret['changes']: ret['result'] = None ret['comment'] = 'The user \'{0}\' will be removed.'.format(name) return ret ret['result'] = True ret['comment'] = 'The user \'{0}\' was removed.'.format(name) return ret
saltstack/salt
salt/states/rabbitmq_user.py
absent
python
def absent(name, runas=None): ''' Ensure the named user is absent name The name of the user to remove runas User to run the command ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} try: user_exists = __salt__['rabbitmq.user_exists'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if user_exists: if not __opts__['test']: try: __salt__['rabbitmq.delete_user'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'name': {'old': name, 'new': ''}}) else: ret['result'] = True ret['comment'] = 'The user \'{0}\' is not present.'.format(name) return ret if __opts__['test'] and ret['changes']: ret['result'] = None ret['comment'] = 'The user \'{0}\' will be removed.'.format(name) return ret ret['result'] = True ret['comment'] = 'The user \'{0}\' was removed.'.format(name) return ret
Ensure the named user is absent name The name of the user to remove runas User to run the command
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_user.py#L232-L272
null
# -*- coding: utf-8 -*- ''' Manage RabbitMQ Users ===================== Example: .. code-block:: yaml rabbit_user: rabbitmq_user.present: - password: password - force: True - tags: - monitoring - user - perms: - '/': - '.*' - '.*' - '.*' - runas: rabbitmq ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.path from salt.ext import six from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) def __virtual__(): ''' Only load if RabbitMQ is installed. ''' return salt.utils.path.which('rabbitmqctl') is not None def _check_perms_changes(name, newperms, runas=None, existing=None): ''' Check whether Rabbitmq user's permissions need to be changed. ''' if not newperms: return False if existing is None: try: existing = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: log.error('Error: %s', err) return False perm_need_change = False for vhost_perms in newperms: for vhost, perms in six.iteritems(vhost_perms): if vhost in existing: existing_vhost = existing[vhost] if perms != existing_vhost: # This checks for setting permissions to nothing in the state, # when previous state runs have already set permissions to # nothing. We don't want to report a change in this case. if existing_vhost == '' and perms == ['', '', '']: continue perm_need_change = True else: perm_need_change = True return perm_need_change def _get_current_tags(name, runas=None): ''' Whether Rabbitmq user's tags need to be changed ''' try: return list(__salt__['rabbitmq.list_users'](runas=runas)[name]) except CommandExecutionError as err: log.error('Error: %s', err) return [] def present(name, password=None, force=False, tags=None, perms=(), runas=None): ''' Ensure the RabbitMQ user exists. name User name password User's password, if one needs to be set force If user exists, forcibly change the password tags Optional list of tags for the user perms A list of dicts with vhost keys and 3-tuple values runas Name of the user to run the command ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} try: user = __salt__['rabbitmq.user_exists'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret passwd_reqs_update = False if user and password is not None: try: if not __salt__['rabbitmq.check_password'](name, password, runas=runas): passwd_reqs_update = True log.debug('RabbitMQ user %s password update required', name) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if user and not any((force, perms, tags, passwd_reqs_update)): log.debug(('RabbitMQ user \'%s\' exists, password is up to' ' date and force is not set.'), name) ret['comment'] = 'User \'{0}\' is already present.'.format(name) ret['result'] = True return ret if not user: ret['changes'].update({'user': {'old': '', 'new': name}}) if __opts__['test']: ret['result'] = None ret['comment'] = 'User \'{0}\' is set to be created.'.format(name) return ret log.debug( 'RabbitMQ user \'%s\' doesn\'t exist - Creating.', name) try: __salt__['rabbitmq.add_user'](name, password, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret else: log.debug('RabbitMQ user \'%s\' exists', name) if force or passwd_reqs_update: if password is not None: if not __opts__['test']: try: __salt__['rabbitmq.change_password'](name, password, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'password': {'old': '', 'new': 'Set password.'}}) else: if not __opts__['test']: log.debug('Password for %s is not set - Clearing password.', name) try: __salt__['rabbitmq.clear_password'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'password': {'old': 'Removed password.', 'new': ''}}) if tags is not None: current_tags = _get_current_tags(name, runas=runas) if isinstance(tags, six.string_types): tags = tags.split() # Diff the tags sets. Symmetric difference operator ^ will give us # any element in one set, but not both if set(tags) ^ set(current_tags): if not __opts__['test']: try: __salt__['rabbitmq.set_user_tags'](name, tags, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret ret['changes'].update({'tags': {'old': current_tags, 'new': tags}}) try: existing_perms = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret if _check_perms_changes(name, perms, runas=runas, existing=existing_perms): for vhost_perm in perms: for vhost, perm in six.iteritems(vhost_perm): if not __opts__['test']: try: __salt__['rabbitmq.set_permissions']( vhost, name, perm[0], perm[1], perm[2], runas=runas ) except CommandExecutionError as err: ret['comment'] = 'Error: {0}'.format(err) return ret new_perms = {vhost: perm} if existing_perms != new_perms: if ret['changes'].get('perms') is None: ret['changes'].update({'perms': {'old': {}, 'new': {}}}) ret['changes']['perms']['old'].update(existing_perms) ret['changes']['perms']['new'].update(new_perms) ret['result'] = True if ret['changes'] == {}: ret['comment'] = '\'{0}\' is already in the desired state.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Configuration for \'{0}\' will change.'.format(name) return ret ret['comment'] = '\'{0}\' was configured.'.format(name) return ret
saltstack/salt
salt/runners/state.py
pause
python
def pause(jid, state_id=None, duration=None): ''' Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.pause'](jid, state_id, duration)
Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L19-L26
null
# -*- coding: utf-8 -*- ''' Execute orchestration functions ''' # Import pytohn libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.loader import salt.utils.event import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError LOGGER = logging.getLogger(__name__) set_pause = salt.utils.functools.alias_function(pause, 'set_pause') def resume(jid, state_id=None): ''' Remove a pause from a jid, allowing it to continue ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.resume'](jid, state_id) rm_pause = salt.utils.functools.alias_function(resume, 'rm_pause') def soft_kill(jid, state_id=None): ''' Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.soft_kill'](jid, state_id) def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None, pillar_enc=None, orchestration_jid=None): ''' .. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) if pillarenv is None and 'pillarenv' in __opts__: pillarenv = __opts__['pillarenv'] if saltenv is None and 'saltenv' in __opts__: saltenv = __opts__['saltenv'] if orchestration_jid is None: orchestration_jid = salt.utils.jid.gen_jid(__opts__) running = minion.functions['state.sls']( mods, test, exclude, pillar=pillar, saltenv=saltenv, pillarenv=pillarenv, pillar_enc=pillar_enc, __pub_jid=orchestration_jid, orchestration_jid=orchestration_jid) ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'} res = __utils__['state.check_result'](ret['data']) if res: ret['retcode'] = 0 else: ret['retcode'] = 1 return ret # Aliases for orchestrate runner orch = salt.utils.functools.alias_function(orchestrate, 'orch') sls = salt.utils.functools.alias_function(orchestrate, 'sls') def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single']( fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.high']( data, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_show_sls(mods, saltenv='base', test=None, queue=False, pillar=None, pillarenv=None, pillar_enc=None): ''' Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.show_sls']( mods, test, queue, pillar=pillar, pillarenv=pillarenv, pillar_enc=pillar_enc, saltenv=saltenv) ret = {minion.opts['id']: running} return ret orch_show_sls = salt.utils.functools.alias_function(orchestrate_show_sls, 'orch_show_sls') def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script. ''' statemod = salt.loader.raw_mod(__opts__, 'state', None) return statemod['state.event']( tagmatch=tagmatch, count=count, quiet=quiet, sock_dir=sock_dir, pretty=pretty, node=node)
saltstack/salt
salt/runners/state.py
resume
python
def resume(jid, state_id=None): ''' Remove a pause from a jid, allowing it to continue ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.resume'](jid, state_id)
Remove a pause from a jid, allowing it to continue
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L32-L37
null
# -*- coding: utf-8 -*- ''' Execute orchestration functions ''' # Import pytohn libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.loader import salt.utils.event import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError LOGGER = logging.getLogger(__name__) def pause(jid, state_id=None, duration=None): ''' Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.pause'](jid, state_id, duration) set_pause = salt.utils.functools.alias_function(pause, 'set_pause') rm_pause = salt.utils.functools.alias_function(resume, 'rm_pause') def soft_kill(jid, state_id=None): ''' Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.soft_kill'](jid, state_id) def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None, pillar_enc=None, orchestration_jid=None): ''' .. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) if pillarenv is None and 'pillarenv' in __opts__: pillarenv = __opts__['pillarenv'] if saltenv is None and 'saltenv' in __opts__: saltenv = __opts__['saltenv'] if orchestration_jid is None: orchestration_jid = salt.utils.jid.gen_jid(__opts__) running = minion.functions['state.sls']( mods, test, exclude, pillar=pillar, saltenv=saltenv, pillarenv=pillarenv, pillar_enc=pillar_enc, __pub_jid=orchestration_jid, orchestration_jid=orchestration_jid) ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'} res = __utils__['state.check_result'](ret['data']) if res: ret['retcode'] = 0 else: ret['retcode'] = 1 return ret # Aliases for orchestrate runner orch = salt.utils.functools.alias_function(orchestrate, 'orch') sls = salt.utils.functools.alias_function(orchestrate, 'sls') def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single']( fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.high']( data, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_show_sls(mods, saltenv='base', test=None, queue=False, pillar=None, pillarenv=None, pillar_enc=None): ''' Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.show_sls']( mods, test, queue, pillar=pillar, pillarenv=pillarenv, pillar_enc=pillar_enc, saltenv=saltenv) ret = {minion.opts['id']: running} return ret orch_show_sls = salt.utils.functools.alias_function(orchestrate_show_sls, 'orch_show_sls') def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script. ''' statemod = salt.loader.raw_mod(__opts__, 'state', None) return statemod['state.event']( tagmatch=tagmatch, count=count, quiet=quiet, sock_dir=sock_dir, pretty=pretty, node=node)
saltstack/salt
salt/runners/state.py
soft_kill
python
def soft_kill(jid, state_id=None): ''' Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.soft_kill'](jid, state_id)
Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L43-L52
null
# -*- coding: utf-8 -*- ''' Execute orchestration functions ''' # Import pytohn libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.loader import salt.utils.event import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError LOGGER = logging.getLogger(__name__) def pause(jid, state_id=None, duration=None): ''' Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.pause'](jid, state_id, duration) set_pause = salt.utils.functools.alias_function(pause, 'set_pause') def resume(jid, state_id=None): ''' Remove a pause from a jid, allowing it to continue ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.resume'](jid, state_id) rm_pause = salt.utils.functools.alias_function(resume, 'rm_pause') def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None, pillar_enc=None, orchestration_jid=None): ''' .. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) if pillarenv is None and 'pillarenv' in __opts__: pillarenv = __opts__['pillarenv'] if saltenv is None and 'saltenv' in __opts__: saltenv = __opts__['saltenv'] if orchestration_jid is None: orchestration_jid = salt.utils.jid.gen_jid(__opts__) running = minion.functions['state.sls']( mods, test, exclude, pillar=pillar, saltenv=saltenv, pillarenv=pillarenv, pillar_enc=pillar_enc, __pub_jid=orchestration_jid, orchestration_jid=orchestration_jid) ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'} res = __utils__['state.check_result'](ret['data']) if res: ret['retcode'] = 0 else: ret['retcode'] = 1 return ret # Aliases for orchestrate runner orch = salt.utils.functools.alias_function(orchestrate, 'orch') sls = salt.utils.functools.alias_function(orchestrate, 'sls') def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single']( fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.high']( data, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_show_sls(mods, saltenv='base', test=None, queue=False, pillar=None, pillarenv=None, pillar_enc=None): ''' Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.show_sls']( mods, test, queue, pillar=pillar, pillarenv=pillarenv, pillar_enc=pillar_enc, saltenv=saltenv) ret = {minion.opts['id']: running} return ret orch_show_sls = salt.utils.functools.alias_function(orchestrate_show_sls, 'orch_show_sls') def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script. ''' statemod = salt.loader.raw_mod(__opts__, 'state', None) return statemod['state.event']( tagmatch=tagmatch, count=count, quiet=quiet, sock_dir=sock_dir, pretty=pretty, node=node)
saltstack/salt
salt/runners/state.py
orchestrate
python
def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None, pillar_enc=None, orchestration_jid=None): ''' .. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) if pillarenv is None and 'pillarenv' in __opts__: pillarenv = __opts__['pillarenv'] if saltenv is None and 'saltenv' in __opts__: saltenv = __opts__['saltenv'] if orchestration_jid is None: orchestration_jid = salt.utils.jid.gen_jid(__opts__) running = minion.functions['state.sls']( mods, test, exclude, pillar=pillar, saltenv=saltenv, pillarenv=pillarenv, pillar_enc=pillar_enc, __pub_jid=orchestration_jid, orchestration_jid=orchestration_jid) ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'} res = __utils__['state.check_result'](ret['data']) if res: ret['retcode'] = 0 else: ret['retcode'] = 1 return ret
.. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L55-L135
[ "def gen_jid(opts=None):\n '''\n Generate a jid\n '''\n if opts is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). '\n 'This will be required starting in {version}.'\n )\n opts = {}\n global LAST_JID_DATETIME # pylint: disable=global-statement\n\n if opts.get('utc_jid', False):\n jid_dt = datetime.datetime.utcnow()\n else:\n jid_dt = datetime.datetime.now()\n if not opts.get('unique_jid', False):\n return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt)\n if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt:\n jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1)\n LAST_JID_DATETIME = jid_dt\n return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid())\n" ]
# -*- coding: utf-8 -*- ''' Execute orchestration functions ''' # Import pytohn libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.loader import salt.utils.event import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError LOGGER = logging.getLogger(__name__) def pause(jid, state_id=None, duration=None): ''' Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.pause'](jid, state_id, duration) set_pause = salt.utils.functools.alias_function(pause, 'set_pause') def resume(jid, state_id=None): ''' Remove a pause from a jid, allowing it to continue ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.resume'](jid, state_id) rm_pause = salt.utils.functools.alias_function(resume, 'rm_pause') def soft_kill(jid, state_id=None): ''' Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.soft_kill'](jid, state_id) # Aliases for orchestrate runner orch = salt.utils.functools.alias_function(orchestrate, 'orch') sls = salt.utils.functools.alias_function(orchestrate, 'sls') def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single']( fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.high']( data, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_show_sls(mods, saltenv='base', test=None, queue=False, pillar=None, pillarenv=None, pillar_enc=None): ''' Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.show_sls']( mods, test, queue, pillar=pillar, pillarenv=pillarenv, pillar_enc=pillar_enc, saltenv=saltenv) ret = {minion.opts['id']: running} return ret orch_show_sls = salt.utils.functools.alias_function(orchestrate_show_sls, 'orch_show_sls') def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script. ''' statemod = salt.loader.raw_mod(__opts__, 'state', None) return statemod['state.event']( tagmatch=tagmatch, count=count, quiet=quiet, sock_dir=sock_dir, pretty=pretty, node=node)
saltstack/salt
salt/runners/state.py
orchestrate_single
python
def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single']( fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret
Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L143-L170
null
# -*- coding: utf-8 -*- ''' Execute orchestration functions ''' # Import pytohn libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.loader import salt.utils.event import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError LOGGER = logging.getLogger(__name__) def pause(jid, state_id=None, duration=None): ''' Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.pause'](jid, state_id, duration) set_pause = salt.utils.functools.alias_function(pause, 'set_pause') def resume(jid, state_id=None): ''' Remove a pause from a jid, allowing it to continue ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.resume'](jid, state_id) rm_pause = salt.utils.functools.alias_function(resume, 'rm_pause') def soft_kill(jid, state_id=None): ''' Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.soft_kill'](jid, state_id) def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None, pillar_enc=None, orchestration_jid=None): ''' .. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) if pillarenv is None and 'pillarenv' in __opts__: pillarenv = __opts__['pillarenv'] if saltenv is None and 'saltenv' in __opts__: saltenv = __opts__['saltenv'] if orchestration_jid is None: orchestration_jid = salt.utils.jid.gen_jid(__opts__) running = minion.functions['state.sls']( mods, test, exclude, pillar=pillar, saltenv=saltenv, pillarenv=pillarenv, pillar_enc=pillar_enc, __pub_jid=orchestration_jid, orchestration_jid=orchestration_jid) ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'} res = __utils__['state.check_result'](ret['data']) if res: ret['retcode'] = 0 else: ret['retcode'] = 1 return ret # Aliases for orchestrate runner orch = salt.utils.functools.alias_function(orchestrate, 'orch') sls = salt.utils.functools.alias_function(orchestrate, 'sls') def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.high']( data, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_show_sls(mods, saltenv='base', test=None, queue=False, pillar=None, pillarenv=None, pillar_enc=None): ''' Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.show_sls']( mods, test, queue, pillar=pillar, pillarenv=pillarenv, pillar_enc=pillar_enc, saltenv=saltenv) ret = {minion.opts['id']: running} return ret orch_show_sls = salt.utils.functools.alias_function(orchestrate_show_sls, 'orch_show_sls') def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script. ''' statemod = salt.loader.raw_mod(__opts__, 'state', None) return statemod['state.event']( tagmatch=tagmatch, count=count, quiet=quiet, sock_dir=sock_dir, pretty=pretty, node=node)
saltstack/salt
salt/runners/state.py
orchestrate_high
python
def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.high']( data, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret
Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L173-L206
null
# -*- coding: utf-8 -*- ''' Execute orchestration functions ''' # Import pytohn libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.loader import salt.utils.event import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError LOGGER = logging.getLogger(__name__) def pause(jid, state_id=None, duration=None): ''' Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.pause'](jid, state_id, duration) set_pause = salt.utils.functools.alias_function(pause, 'set_pause') def resume(jid, state_id=None): ''' Remove a pause from a jid, allowing it to continue ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.resume'](jid, state_id) rm_pause = salt.utils.functools.alias_function(resume, 'rm_pause') def soft_kill(jid, state_id=None): ''' Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.soft_kill'](jid, state_id) def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None, pillar_enc=None, orchestration_jid=None): ''' .. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) if pillarenv is None and 'pillarenv' in __opts__: pillarenv = __opts__['pillarenv'] if saltenv is None and 'saltenv' in __opts__: saltenv = __opts__['saltenv'] if orchestration_jid is None: orchestration_jid = salt.utils.jid.gen_jid(__opts__) running = minion.functions['state.sls']( mods, test, exclude, pillar=pillar, saltenv=saltenv, pillarenv=pillarenv, pillar_enc=pillar_enc, __pub_jid=orchestration_jid, orchestration_jid=orchestration_jid) ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'} res = __utils__['state.check_result'](ret['data']) if res: ret['retcode'] = 0 else: ret['retcode'] = 1 return ret # Aliases for orchestrate runner orch = salt.utils.functools.alias_function(orchestrate, 'orch') sls = salt.utils.functools.alias_function(orchestrate, 'sls') def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single']( fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_show_sls(mods, saltenv='base', test=None, queue=False, pillar=None, pillarenv=None, pillar_enc=None): ''' Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.show_sls']( mods, test, queue, pillar=pillar, pillarenv=pillarenv, pillar_enc=pillar_enc, saltenv=saltenv) ret = {minion.opts['id']: running} return ret orch_show_sls = salt.utils.functools.alias_function(orchestrate_show_sls, 'orch_show_sls') def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script. ''' statemod = salt.loader.raw_mod(__opts__, 'state', None) return statemod['state.event']( tagmatch=tagmatch, count=count, quiet=quiet, sock_dir=sock_dir, pretty=pretty, node=node)
saltstack/salt
salt/runners/state.py
orchestrate_show_sls
python
def orchestrate_show_sls(mods, saltenv='base', test=None, queue=False, pillar=None, pillarenv=None, pillar_enc=None): ''' Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.show_sls']( mods, test, queue, pillar=pillar, pillarenv=pillarenv, pillar_enc=pillar_enc, saltenv=saltenv) ret = {minion.opts['id']: running} return ret
Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L209-L245
null
# -*- coding: utf-8 -*- ''' Execute orchestration functions ''' # Import pytohn libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.loader import salt.utils.event import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError LOGGER = logging.getLogger(__name__) def pause(jid, state_id=None, duration=None): ''' Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.pause'](jid, state_id, duration) set_pause = salt.utils.functools.alias_function(pause, 'set_pause') def resume(jid, state_id=None): ''' Remove a pause from a jid, allowing it to continue ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.resume'](jid, state_id) rm_pause = salt.utils.functools.alias_function(resume, 'rm_pause') def soft_kill(jid, state_id=None): ''' Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.soft_kill'](jid, state_id) def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None, pillar_enc=None, orchestration_jid=None): ''' .. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) if pillarenv is None and 'pillarenv' in __opts__: pillarenv = __opts__['pillarenv'] if saltenv is None and 'saltenv' in __opts__: saltenv = __opts__['saltenv'] if orchestration_jid is None: orchestration_jid = salt.utils.jid.gen_jid(__opts__) running = minion.functions['state.sls']( mods, test, exclude, pillar=pillar, saltenv=saltenv, pillarenv=pillarenv, pillar_enc=pillar_enc, __pub_jid=orchestration_jid, orchestration_jid=orchestration_jid) ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'} res = __utils__['state.check_result'](ret['data']) if res: ret['retcode'] = 0 else: ret['retcode'] = 1 return ret # Aliases for orchestrate runner orch = salt.utils.functools.alias_function(orchestrate, 'orch') sls = salt.utils.functools.alias_function(orchestrate, 'sls') def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single']( fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.high']( data, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret orch_show_sls = salt.utils.functools.alias_function(orchestrate_show_sls, 'orch_show_sls') def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script. ''' statemod = salt.loader.raw_mod(__opts__, 'state', None) return statemod['state.event']( tagmatch=tagmatch, count=count, quiet=quiet, sock_dir=sock_dir, pretty=pretty, node=node)
saltstack/salt
salt/runners/state.py
event
python
def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script. ''' statemod = salt.loader.raw_mod(__opts__, 'state', None) return statemod['state.event']( tagmatch=tagmatch, count=count, quiet=quiet, sock_dir=sock_dir, pretty=pretty, node=node)
r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly from the CLI. Enable debug logging to see ignored events. :param tagmatch: the event is written to stdout for each tag that matches this glob or regular expression. :param count: this number is decremented for each event that matches the ``tagmatch`` parameter; pass ``-1`` to listen forever. :param quiet: do not print to stdout; just block :param sock_dir: path to the Salt master's event socket file. :param pretty: Output the JSON all on a single line if ``False`` (useful for shell tools); pretty-print the JSON output if ``True``. :param node: Watch the minion-side or master-side event bus. .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash # Reboot a minion and run highstate when it comes back online salt 'jerry' system.reboot && \\ salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\ salt 'jerry' state.highstate # Reboot multiple minions and run highstate when all are back online salt -L 'kevin,stewart,dave' system.reboot && \\ salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\ salt -L 'kevin,stewart,dave' state.highstate # Watch the event bus forever in a shell while-loop. salt-run state.event | while read -r tag data; do echo $tag echo $data | jq --color-output . done .. seealso:: See :blob:`tests/eventlisten.sh` for an example of usage within a shell script.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L251-L313
null
# -*- coding: utf-8 -*- ''' Execute orchestration functions ''' # Import pytohn libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.loader import salt.utils.event import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError LOGGER = logging.getLogger(__name__) def pause(jid, state_id=None, duration=None): ''' Set up a state id pause, this instructs a running state to pause at a given state id. This needs to pass in the jid of the running state and can optionally pass in a duration in seconds. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.pause'](jid, state_id, duration) set_pause = salt.utils.functools.alias_function(pause, 'set_pause') def resume(jid, state_id=None): ''' Remove a pause from a jid, allowing it to continue ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.resume'](jid, state_id) rm_pause = salt.utils.functools.alias_function(resume, 'rm_pause') def soft_kill(jid, state_id=None): ''' Set up a state run to die before executing the given state id, this instructs a running state to safely exit at a given state id. This needs to pass in the jid of the running state. If a state_id is not passed then the jid referenced will be safely exited at the beginning of the next state run. ''' minion = salt.minion.MasterMinion(__opts__) minion.functions['state.soft_kill'](jid, state_id) def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None, pillar_enc=None, orchestration_jid=None): ''' .. versionadded:: 0.17.0 Execute a state run from the master, used as a powerful orchestration system. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:mod:`Docs for the master-side state module <salt.states.saltmod>` CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver salt-run state.orchestrate webserver saltenv=dev test=True salt-run state.orchestrate webserver saltenv=dev pillarenv=aws .. versionchanged:: 2014.1.1 Runner renamed from ``state.sls`` to ``state.orchestrate`` .. versionchanged:: 2014.7.0 Runner uses the pillar variable .. versionchanged:: develop Runner uses the pillar_enc variable that allows renderers to render the pillar. This is usable when supplying the contents of a file as pillar, and the file contains gpg-encrypted entries. .. seealso:: GPG renderer documentation CLI Examples: .. code-block:: bash salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) if pillarenv is None and 'pillarenv' in __opts__: pillarenv = __opts__['pillarenv'] if saltenv is None and 'saltenv' in __opts__: saltenv = __opts__['saltenv'] if orchestration_jid is None: orchestration_jid = salt.utils.jid.gen_jid(__opts__) running = minion.functions['state.sls']( mods, test, exclude, pillar=pillar, saltenv=saltenv, pillarenv=pillarenv, pillar_enc=pillar_enc, __pub_jid=orchestration_jid, orchestration_jid=orchestration_jid) ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'} res = __utils__['state.check_result'](ret['data']) if res: ret['retcode'] = 0 else: ret['retcode'] = 1 return ret # Aliases for orchestrate runner orch = salt.utils.functools.alias_function(orchestrate, 'orch') sls = salt.utils.functools.alias_function(orchestrate, 'sls') def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_single fun=salt.wheel name=key.list_all ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single']( fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], }]}, }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary' ) __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.high']( data, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret def orchestrate_show_sls(mods, saltenv='base', test=None, queue=False, pillar=None, pillarenv=None, pillar_enc=None): ''' Display the state data from a specific sls, or list of sls files, after being render using the master minion. Note, the master minion adds a "_master" suffix to it's minion id. .. seealso:: The state.show_sls module function CLI Example: .. code-block:: bash salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' ''' if pillar is not None and not isinstance(pillar, dict): raise SaltInvocationError( 'Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.show_sls']( mods, test, queue, pillar=pillar, pillarenv=pillarenv, pillar_enc=pillar_enc, saltenv=saltenv) ret = {minion.opts['id']: running} return ret orch_show_sls = salt.utils.functools.alias_function(orchestrate_show_sls, 'orch_show_sls')
saltstack/salt
salt/modules/smtp.py
send_msg
python
def send_msg(recipient, message, subject='Message from Salt', sender=None, server=None, use_ssl='True', username=None, password=None, profile=None, attachments=None): ''' Send a message to an SMTP recipient. Designed for use in states. CLI Examples: .. code-block:: bash salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' profile='my-smtp-account' salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com' salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com' attachments="['/var/log/messages']" ''' if profile: creds = __salt__['config.option'](profile) server = creds.get('smtp.server') use_ssl = creds.get('smtp.tls') sender = creds.get('smtp.sender') username = creds.get('smtp.username') password = creds.get('smtp.password') if attachments: msg = email.mime.multipart.MIMEMultipart() msg.attach(email.mime.text.MIMEText(message)) else: msg = email.mime.text.MIMEText(message) msg['Subject'] = subject msg['From'] = sender msg['To'] = recipient recipients = [r.strip() for r in recipient.split(',')] try: if use_ssl in ['True', 'true']: smtpconn = smtplib.SMTP_SSL(server) else: smtpconn = smtplib.SMTP(server) except socket.gaierror as _error: log.debug("Exception: %s", _error) return False if use_ssl not in ('True', 'true'): smtpconn.ehlo() if smtpconn.has_extn('STARTTLS'): try: smtpconn.starttls() except smtplib.SMTPHeloError: log.debug("The server didn’t reply properly \ to the HELO greeting.") return False except smtplib.SMTPException: log.debug("The server does not support the STARTTLS extension.") return False except RuntimeError: log.debug("SSL/TLS support is not available \ to your Python interpreter.") return False smtpconn.ehlo() if username and password: try: smtpconn.login(username, password) except smtplib.SMTPAuthenticationError as _error: log.debug("SMTP Authentication Failure") return False if attachments: for f in attachments: name = os.path.basename(f) with salt.utils.files.fopen(f, 'rb') as fin: att = email.mime.application.MIMEApplication(fin.read(), Name=name) att['Content-Disposition'] = 'attachment; filename="{0}"'.format(name) msg.attach(att) try: smtpconn.sendmail(sender, recipients, msg.as_string()) except smtplib.SMTPRecipientsRefused: log.debug("All recipients were refused.") return False except smtplib.SMTPHeloError: log.debug("The server didn’t reply properly to the HELO greeting.") return False except smtplib.SMTPSenderRefused: log.debug("The server didn’t accept the %s.", sender) return False except smtplib.SMTPDataError: log.debug("The server replied with an unexpected error code.") return False smtpconn.quit() return True
Send a message to an SMTP recipient. Designed for use in states. CLI Examples: .. code-block:: bash salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' profile='my-smtp-account' salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com' salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com' attachments="['/var/log/messages']"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smtp.py#L77-L175
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n" ]
# -*- coding: utf-8 -*- ''' Module for Sending Messages via SMTP .. versionadded:: 2014.7.0 :depends: - smtplib python module :configuration: This module can be used by either passing a jid and password directly to send_message, or by specifying the name of a configuration profile in the minion config, minion pillar, or master config. For example: .. code-block:: yaml my-smtp-login: smtp.server: smtp.domain.com smtp.tls: True smtp.sender: admin@domain.com smtp.username: myuser smtp.password: verybadpass The resourcename refers to the resource that is using this account. It is user-definable, and optional. The following configurations are both valid: .. code-block:: yaml my-smtp-login: smtp.server: smtp.domain.com smtp.tls: True smtp.sender: admin@domain.com smtp.username: myuser smtp.password: verybadpass another-smtp-login: smtp.server: smtp.domain.com smtp.tls: True smtp.sender: admin@domain.com smtp.username: myuser smtp.password: verybadpass ''' from __future__ import absolute_import, unicode_literals, print_function import logging import os import socket # Import salt libs import salt.utils.files log = logging.getLogger(__name__) HAS_LIBS = False try: import smtplib import email.mime.text import email.mime.application import email.mime.multipart HAS_LIBS = True except ImportError: pass __virtualname__ = 'smtp' def __virtual__(): ''' Only load this module if smtplib is available on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'This module is only loaded if smtplib is available')
saltstack/salt
salt/modules/bluecoat_sslv.py
add_distinguished_name
python
def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response)
Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L76-L98
[ "def _validate_change_result(response):\n if response['result'] == \"true\" or response['result'] is True:\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/modules/bluecoat_sslv.py
add_distinguished_name_list
python
def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response)
Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L101-L121
[ "def _validate_change_result(response):\n if response['result'] == \"true\" or response['result'] is True:\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/modules/bluecoat_sslv.py
add_domain_name
python
def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response)
Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L124-L146
[ "def _validate_change_result(response):\n if response['result'] == \"true\" or response['result'] is True:\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/modules/bluecoat_sslv.py
add_domain_name_list
python
def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response)
Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L149-L169
[ "def _validate_change_result(response):\n if response['result'] == \"true\" or response['result'] is True:\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/modules/bluecoat_sslv.py
add_ip_address
python
def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response)
Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L172-L194
[ "def _validate_change_result(response):\n if response['result'] == \"true\" or response['result'] is True:\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/modules/bluecoat_sslv.py
add_ip_address_list
python
def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response)
Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L197-L217
[ "def _validate_change_result(response):\n if response['result'] == \"true\" or response['result'] is True:\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/modules/bluecoat_sslv.py
get_distinguished_name_list
python
def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name')
Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L220-L240
[ "def _convert_to_list(response, item_key):\n full_list = []\n for item in response['result'][0]:\n full_list.append(item[item_key])\n return full_list\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/modules/bluecoat_sslv.py
get_domain_list
python
def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name')
Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L264-L284
[ "def _convert_to_list(response, item_key):\n full_list = []\n for item in response['result'][0]:\n full_list.append(item[item_key])\n return full_list\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/modules/bluecoat_sslv.py
get_ip_address_list
python
def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name')
Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L308-L328
[ "def _convert_to_list(response, item_key):\n full_list = []\n for item in response['result'][0]:\n full_list.append(item[item_key])\n return full_list\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Blue Coat SSL Visibility compatibility to Salt. :codeauthor: Spencer Ervin <spencer_ervin@hotmail.com> :maturity: new :depends: none :platform: unix 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:`Blue Coat SSL Visibility Proxy Module <salt.proxy.bluecoat_sslv>` About ===== This execution module was designed to handle connections to a Blue Coat SSL Visibility server. This module adds support to send connections directly to the device through the rest API. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs import salt.utils.platform import salt.proxy.bluecoat_sslv log = logging.getLogger(__name__) __virtualname__ = 'bluecoat_sslv' def __virtual__(): ''' Will load for the bluecoat_sslv proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'bluecoat_sslv': return __virtualname__ except KeyError: pass return False, 'The bluecoat_sslv execution module can only be loaded for bluecoat_sslv proxy minions.' def _validate_change_result(response): if response['result'] == "true" or response['result'] is True: return True return False def _convert_to_list(response, item_key): full_list = [] for item in response['result'][0]: full_list.append(item[item_key]) return full_list def _collapse_dict_format(response): decoded = {} for item in response: decoded[item['key']] = item['value'] return decoded def add_distinguished_name(list_name, item_name): ''' Adds a distinguished name to a distinguished name list. list_name(str): The name of the specific policy distinguished name list to append to. item_name(str): The distinguished name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_distinguished_name_list(list_name): ''' Add a list of policy distinguished names. list_name(str): The name of the specific policy distinguished name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_distinguished_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_domain_name_list(list_name): ''' Add a list of policy domain names. list_name(str): The name of the specific policy domain name list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_domain_names_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def add_ip_address_list(list_name): ''' Retrieves a list of all IP address lists. list_name(str): The name of the specific IP address list to add. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses_list", "params": [{"list_name": list_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response) def get_distinguished_name_list(list_name): ''' Retrieves a specific policy distinguished name list. list_name(str): The name of the specific policy distinguished name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_distinguished_name_lists(): ''' Retrieves a list of all policy distinguished name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_distinguished_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_distinguished_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_domain_list(list_name): ''' Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name') def get_domain_lists(): ''' Retrieves a list of all policy domain name lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_name_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ip_address_lists(): ''' Retrieves a list of all IP address lists. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_lists ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses_list", "params": [0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'list_name') def get_ipv4_config(): ''' Retrieves IPv4 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv4_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv4", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_ipv6_config(): ''' Retrieves IPv6 configuration from the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ipv6_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config_ipv6", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_management_config(): ''' Retrieves management configuration for the device. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_management_config ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_config", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return response['result'] def get_platform(): ''' Retrieves platform information, such as serial number and part number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_platform ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_chassis", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result']) def get_software(): ''' Retrieves platform software information, such as software version number. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_software ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_platform_information_sw_rev", "params": []} response = __proxy__['bluecoat_sslv.call'](payload, False) return _collapse_dict_format(response['result'])
saltstack/salt
salt/utils/win_runas.py
runas
python
def runas(cmdLine, username, password=None, cwd=None): ''' Run a command as another user. If the process is running as an admin or system account this method does not require a password. Other non privileged accounts need to provide a password for the user to runas. Commands are run in with the highest level privileges possible for the account provided. ''' # Elevate the token from the current process access = ( win32security.TOKEN_QUERY | win32security.TOKEN_ADJUST_PRIVILEGES ) th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), access) salt.platform.win.elevate_token(th) # Try to impersonate the SYSTEM user. This process needs to be running as a # user who as been granted the SeImpersonatePrivilege, Administrator # accounts have this permission by default. try: impersonation_token = salt.platform.win.impersonate_sid( salt.platform.win.SYSTEM_SID, session_id=0, privs=['SeTcbPrivilege'], ) except WindowsError: # pylint: disable=undefined-variable log.debug("Unable to impersonate SYSTEM user") impersonation_token = None # Impersonation of the SYSTEM user failed. Fallback to an un-privileged # runas. if not impersonation_token: log.debug("No impersonation token, using unprivileged runas") return runas_unpriv(cmdLine, username, password, cwd) username, domain = split_username(username) # Validate the domain and sid exist for the username try: _, domain, _ = win32security.LookupAccountName(domain, username) except pywintypes.error as exc: message = win32api.FormatMessage(exc.winerror).rstrip('\n') raise CommandExecutionError(message) if domain == 'NT AUTHORITY': # Logon as a system level account, SYSTEM, LOCAL SERVICE, or NETWORK # SERVICE. logonType = win32con.LOGON32_LOGON_SERVICE user_token = win32security.LogonUser( username, domain, '', win32con.LOGON32_LOGON_SERVICE, win32con.LOGON32_PROVIDER_DEFAULT, ) elif password: # Login with a password. user_token = win32security.LogonUser( username, domain, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT, ) else: # Login without a password. This always returns an elevated token. user_token = salt.platform.win.logon_msv1_s4u(username).Token # Get a linked user token to elevate if needed elevation_type = win32security.GetTokenInformation( user_token, win32security.TokenElevationType ) if elevation_type > 1: user_token = win32security.GetTokenInformation( user_token, win32security.TokenLinkedToken ) # Elevate the user token salt.platform.win.elevate_token(user_token) # Make sure the user's token has access to a windows station and desktop salt.platform.win.grant_winsta_and_desktop(user_token) # Create pipes for standard in, out and error streams security_attributes = win32security.SECURITY_ATTRIBUTES() security_attributes.bInheritHandle = 1 stdin_read, stdin_write = win32pipe.CreatePipe(security_attributes, 0) stdin_read = salt.platform.win.make_inheritable(stdin_read) stdout_read, stdout_write = win32pipe.CreatePipe(security_attributes, 0) stdout_write = salt.platform.win.make_inheritable(stdout_write) stderr_read, stderr_write = win32pipe.CreatePipe(security_attributes, 0) stderr_write = salt.platform.win.make_inheritable(stderr_write) # Run the process without showing a window. creationflags = ( win32process.CREATE_NO_WINDOW | win32process.CREATE_NEW_CONSOLE | win32process.CREATE_SUSPENDED ) startup_info = salt.platform.win.STARTUPINFO( dwFlags=win32con.STARTF_USESTDHANDLES, hStdInput=stdin_read.handle, hStdOutput=stdout_write.handle, hStdError=stderr_write.handle, ) # Create the environment for the user env = win32profile.CreateEnvironmentBlock(user_token, False) # Start the process in a suspended state. process_info = salt.platform.win.CreateProcessWithTokenW( int(user_token), logonflags=1, applicationname=None, commandline=cmdLine, currentdirectory=cwd, creationflags=creationflags, startupinfo=startup_info, environment=env, ) hProcess = process_info.hProcess hThread = process_info.hThread dwProcessId = process_info.dwProcessId dwThreadId = process_info.dwThreadId salt.platform.win.kernel32.CloseHandle(stdin_write.handle) salt.platform.win.kernel32.CloseHandle(stdout_write.handle) salt.platform.win.kernel32.CloseHandle(stderr_write.handle) ret = {'pid': dwProcessId} # Resume the process psutil.Process(dwProcessId).resume() # Wait for the process to exit and get it's return code. if win32event.WaitForSingleObject(hProcess, win32event.INFINITE) == win32con.WAIT_OBJECT_0: exitcode = win32process.GetExitCodeProcess(hProcess) ret['retcode'] = exitcode # Read standard out fd_out = msvcrt.open_osfhandle(stdout_read.handle, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_out, 'r') as f_out: stdout = f_out.read() ret['stdout'] = stdout # Read standard error fd_err = msvcrt.open_osfhandle(stderr_read.handle, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_err, 'r') as f_err: stderr = f_err.read() ret['stderr'] = stderr salt.platform.win.kernel32.CloseHandle(hProcess) win32api.CloseHandle(user_token) if impersonation_token: win32security.RevertToSelf() win32api.CloseHandle(impersonation_token) return ret
Run a command as another user. If the process is running as an admin or system account this method does not require a password. Other non privileged accounts need to provide a password for the user to runas. Commands are run in with the highest level privileges possible for the account provided.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_runas.py#L62-L224
[ "def logon_msv1_s4u(name, local_groups=None, origin_name=py_origin_name,\n source_context=None):\n domain = ctypes.create_unicode_buffer(MAX_COMPUTER_NAME_LENGTH + 1)\n length = wintypes.DWORD(len(domain))\n kernel32.GetComputerNameW(domain, ctypes.byref(length))\n return lsa_logon_user(MSV1_0_S4U_LOGON(name, domain.value),\n local_groups, origin_name, source_context)\n", "def grant_winsta_and_desktop(th):\n '''\n Grant the token's user access to the current process's window station and\n desktop.\n '''\n current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]\n # Add permissions for the sid to the current windows station and thread id.\n # This prevents windows error 0xC0000142.\n winsta = win32process.GetProcessWindowStation()\n set_user_perm(winsta, WINSTA_ALL, current_sid)\n desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())\n set_user_perm(desktop, DESKTOP_ALL, current_sid)\n", "def CreateProcessWithTokenW(token,\n logonflags=0,\n applicationname=None,\n commandline=None,\n creationflags=0,\n environment=None,\n currentdirectory=None,\n startupinfo=None):\n creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT\n if commandline is not None:\n commandline = ctypes.create_unicode_buffer(commandline)\n if startupinfo is None:\n startupinfo = STARTUPINFO()\n if currentdirectory is not None:\n currentdirectory = ctypes.create_unicode_buffer(currentdirectory)\n if environment:\n environment = ctypes.pointer(\n environment_string(environment)\n )\n process_info = PROCESS_INFORMATION()\n ret = advapi32.CreateProcessWithTokenW(\n token,\n logonflags,\n applicationname,\n commandline,\n creationflags,\n environment,\n currentdirectory,\n ctypes.byref(startupinfo),\n ctypes.byref(process_info),\n )\n if ret == 0:\n winerr = win32api.GetLastError()\n exc = WindowsError(win32api.FormatMessage(winerr)) # pylint: disable=undefined-variable\n exc.winerror = winerr\n raise exc\n return process_info\n", "def impersonate_sid(sid, session_id=None, privs=None):\n '''\n Find an existing process token for the given sid and impersonate the token.\n '''\n for tok in enumerate_tokens(sid, session_id, privs):\n tok = dup_token(tok)\n elevate_token(tok)\n if win32security.ImpersonateLoggedOnUser(tok) == 0:\n raise WindowsError(\"Impersonation failure\") # pylint: disable=undefined-variable\n return tok\n raise WindowsError(\"Impersonation failure\") # pylint: disable=undefined-variable\n", "def elevate_token(th):\n '''\n Set all token priviledges to enabled\n '''\n # Get list of privileges this token contains\n privileges = win32security.GetTokenInformation(\n th, win32security.TokenPrivileges)\n\n # Create a set of all privileges to be enabled\n enable_privs = set()\n for luid, flags in privileges:\n enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))\n\n # Enable the privileges\n if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:\n raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) # pylint: disable=undefined-variable\n", "def make_inheritable(token):\n '''Create an inheritable handle'''\n return win32api.DuplicateHandle(\n win32api.GetCurrentProcess(),\n token,\n win32api.GetCurrentProcess(),\n 0,\n 1,\n win32con.DUPLICATE_SAME_ACCESS\n )\n", "def split_username(username):\n # TODO: Is there a windows api for this?\n domain = '.'\n if '@' in username:\n username, domain = username.split('@')\n if '\\\\' in username:\n domain, username = username.split('\\\\')\n return username, domain\n", "def runas_unpriv(cmd, username, password, cwd=None):\n '''\n Runas that works for non-priviledged users\n '''\n # Create a pipe to set as stdout in the child. The write handle needs to be\n # inheritable.\n c2pread, c2pwrite = salt.platform.win.CreatePipe(\n inherit_read=False, inherit_write=True,\n )\n errread, errwrite = salt.platform.win.CreatePipe(\n inherit_read=False, inherit_write=True,\n )\n\n # Create inheritable copy of the stdin\n stdin = salt.platform.win.kernel32.GetStdHandle(\n salt.platform.win.STD_INPUT_HANDLE,\n )\n dupin = salt.platform.win.DuplicateHandle(srchandle=stdin, inherit=True)\n\n # Get startup info structure\n startup_info = salt.platform.win.STARTUPINFO(\n dwFlags=win32con.STARTF_USESTDHANDLES,\n hStdInput=dupin,\n hStdOutput=c2pwrite,\n hStdError=errwrite,\n )\n\n username, domain = split_username(username)\n\n # Run command and return process info structure\n process_info = salt.platform.win.CreateProcessWithLogonW(\n username=username,\n domain=domain,\n password=password,\n logonflags=salt.platform.win.LOGON_WITH_PROFILE,\n commandline=cmd,\n startupinfo=startup_info,\n currentdirectory=cwd)\n\n salt.platform.win.kernel32.CloseHandle(dupin)\n salt.platform.win.kernel32.CloseHandle(c2pwrite)\n salt.platform.win.kernel32.CloseHandle(errwrite)\n salt.platform.win.kernel32.CloseHandle(process_info.hThread)\n\n # Initialize ret and set first element\n ret = {'pid': process_info.dwProcessId}\n\n # Get Standard Out\n fd_out = msvcrt.open_osfhandle(c2pread, os.O_RDONLY | os.O_TEXT)\n with os.fdopen(fd_out, 'r') as f_out:\n ret['stdout'] = f_out.read()\n\n # Get Standard Error\n fd_err = msvcrt.open_osfhandle(errread, os.O_RDONLY | os.O_TEXT)\n with os.fdopen(fd_err, 'r') as f_err:\n ret['stderr'] = f_err.read()\n\n # Get Return Code\n if salt.platform.win.kernel32.WaitForSingleObject(process_info.hProcess, win32event.INFINITE) == \\\n win32con.WAIT_OBJECT_0:\n exitcode = salt.platform.win.wintypes.DWORD()\n salt.platform.win.kernel32.GetExitCodeProcess(process_info.hProcess,\n ctypes.byref(exitcode))\n ret['retcode'] = exitcode.value\n\n # Close handle to process\n salt.platform.win.kernel32.CloseHandle(process_info.hProcess)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Run processes as a different user in Windows ''' from __future__ import absolute_import, unicode_literals # Import Python Libraries import ctypes import os import logging # Import Third Party Libs try: import psutil HAS_PSUTIL = True except ImportError: HAS_PSUTIL = False try: import win32api import win32con import win32process import win32security import win32pipe import win32event import win32profile import msvcrt import salt.platform.win import pywintypes HAS_WIN32 = True except ImportError: HAS_WIN32 = False # Import Salt Libs from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Although utils are often directly imported, it is also possible to use the # loader. def __virtual__(): ''' Only load if Win32 Libraries are installed ''' if not HAS_WIN32 or not HAS_PSUTIL: return False, 'This utility requires pywin32 and psutil' return 'win_runas' def split_username(username): # TODO: Is there a windows api for this? domain = '.' if '@' in username: username, domain = username.split('@') if '\\' in username: domain, username = username.split('\\') return username, domain def runas_unpriv(cmd, username, password, cwd=None): ''' Runas that works for non-priviledged users ''' # Create a pipe to set as stdout in the child. The write handle needs to be # inheritable. c2pread, c2pwrite = salt.platform.win.CreatePipe( inherit_read=False, inherit_write=True, ) errread, errwrite = salt.platform.win.CreatePipe( inherit_read=False, inherit_write=True, ) # Create inheritable copy of the stdin stdin = salt.platform.win.kernel32.GetStdHandle( salt.platform.win.STD_INPUT_HANDLE, ) dupin = salt.platform.win.DuplicateHandle(srchandle=stdin, inherit=True) # Get startup info structure startup_info = salt.platform.win.STARTUPINFO( dwFlags=win32con.STARTF_USESTDHANDLES, hStdInput=dupin, hStdOutput=c2pwrite, hStdError=errwrite, ) username, domain = split_username(username) # Run command and return process info structure process_info = salt.platform.win.CreateProcessWithLogonW( username=username, domain=domain, password=password, logonflags=salt.platform.win.LOGON_WITH_PROFILE, commandline=cmd, startupinfo=startup_info, currentdirectory=cwd) salt.platform.win.kernel32.CloseHandle(dupin) salt.platform.win.kernel32.CloseHandle(c2pwrite) salt.platform.win.kernel32.CloseHandle(errwrite) salt.platform.win.kernel32.CloseHandle(process_info.hThread) # Initialize ret and set first element ret = {'pid': process_info.dwProcessId} # Get Standard Out fd_out = msvcrt.open_osfhandle(c2pread, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_out, 'r') as f_out: ret['stdout'] = f_out.read() # Get Standard Error fd_err = msvcrt.open_osfhandle(errread, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_err, 'r') as f_err: ret['stderr'] = f_err.read() # Get Return Code if salt.platform.win.kernel32.WaitForSingleObject(process_info.hProcess, win32event.INFINITE) == \ win32con.WAIT_OBJECT_0: exitcode = salt.platform.win.wintypes.DWORD() salt.platform.win.kernel32.GetExitCodeProcess(process_info.hProcess, ctypes.byref(exitcode)) ret['retcode'] = exitcode.value # Close handle to process salt.platform.win.kernel32.CloseHandle(process_info.hProcess) return ret
saltstack/salt
salt/utils/win_runas.py
runas_unpriv
python
def runas_unpriv(cmd, username, password, cwd=None): ''' Runas that works for non-priviledged users ''' # Create a pipe to set as stdout in the child. The write handle needs to be # inheritable. c2pread, c2pwrite = salt.platform.win.CreatePipe( inherit_read=False, inherit_write=True, ) errread, errwrite = salt.platform.win.CreatePipe( inherit_read=False, inherit_write=True, ) # Create inheritable copy of the stdin stdin = salt.platform.win.kernel32.GetStdHandle( salt.platform.win.STD_INPUT_HANDLE, ) dupin = salt.platform.win.DuplicateHandle(srchandle=stdin, inherit=True) # Get startup info structure startup_info = salt.platform.win.STARTUPINFO( dwFlags=win32con.STARTF_USESTDHANDLES, hStdInput=dupin, hStdOutput=c2pwrite, hStdError=errwrite, ) username, domain = split_username(username) # Run command and return process info structure process_info = salt.platform.win.CreateProcessWithLogonW( username=username, domain=domain, password=password, logonflags=salt.platform.win.LOGON_WITH_PROFILE, commandline=cmd, startupinfo=startup_info, currentdirectory=cwd) salt.platform.win.kernel32.CloseHandle(dupin) salt.platform.win.kernel32.CloseHandle(c2pwrite) salt.platform.win.kernel32.CloseHandle(errwrite) salt.platform.win.kernel32.CloseHandle(process_info.hThread) # Initialize ret and set first element ret = {'pid': process_info.dwProcessId} # Get Standard Out fd_out = msvcrt.open_osfhandle(c2pread, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_out, 'r') as f_out: ret['stdout'] = f_out.read() # Get Standard Error fd_err = msvcrt.open_osfhandle(errread, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_err, 'r') as f_err: ret['stderr'] = f_err.read() # Get Return Code if salt.platform.win.kernel32.WaitForSingleObject(process_info.hProcess, win32event.INFINITE) == \ win32con.WAIT_OBJECT_0: exitcode = salt.platform.win.wintypes.DWORD() salt.platform.win.kernel32.GetExitCodeProcess(process_info.hProcess, ctypes.byref(exitcode)) ret['retcode'] = exitcode.value # Close handle to process salt.platform.win.kernel32.CloseHandle(process_info.hProcess) return ret
Runas that works for non-priviledged users
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_runas.py#L227-L295
[ "def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(),\n srchandle=kernel32.GetCurrentProcess(),\n htgt=kernel32.GetCurrentProcess(),\n access=0, inherit=False,\n options=win32con.DUPLICATE_SAME_ACCESS):\n tgthandle = wintypes.HANDLE()\n kernel32.DuplicateHandle(hsrc, srchandle,\n htgt, ctypes.byref(tgthandle),\n access, inherit, options)\n return tgthandle.value\n", "def CreatePipe(inherit_read=False, inherit_write=False):\n read, write = wintypes.HANDLE(), wintypes.HANDLE()\n kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0)\n if inherit_read:\n kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT,\n win32con.HANDLE_FLAG_INHERIT)\n if inherit_write:\n kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT,\n win32con.HANDLE_FLAG_INHERIT)\n return read.value, write.value\n", "def CreateProcessWithLogonW(username=None, domain=None, password=None,\n logonflags=0, applicationname=None, commandline=None, creationflags=0,\n environment=None, currentdirectory=None, startupinfo=None):\n creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT\n if commandline is not None:\n commandline = ctypes.create_unicode_buffer(commandline)\n if startupinfo is None:\n startupinfo = STARTUPINFO()\n process_info = PROCESS_INFORMATION()\n advapi32.CreateProcessWithLogonW(\n username,\n domain,\n password,\n logonflags,\n applicationname,\n commandline,\n creationflags,\n environment,\n currentdirectory,\n ctypes.byref(startupinfo),\n ctypes.byref(process_info),\n )\n return process_info\n", "def split_username(username):\n # TODO: Is there a windows api for this?\n domain = '.'\n if '@' in username:\n username, domain = username.split('@')\n if '\\\\' in username:\n domain, username = username.split('\\\\')\n return username, domain\n" ]
# -*- coding: utf-8 -*- ''' Run processes as a different user in Windows ''' from __future__ import absolute_import, unicode_literals # Import Python Libraries import ctypes import os import logging # Import Third Party Libs try: import psutil HAS_PSUTIL = True except ImportError: HAS_PSUTIL = False try: import win32api import win32con import win32process import win32security import win32pipe import win32event import win32profile import msvcrt import salt.platform.win import pywintypes HAS_WIN32 = True except ImportError: HAS_WIN32 = False # Import Salt Libs from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Although utils are often directly imported, it is also possible to use the # loader. def __virtual__(): ''' Only load if Win32 Libraries are installed ''' if not HAS_WIN32 or not HAS_PSUTIL: return False, 'This utility requires pywin32 and psutil' return 'win_runas' def split_username(username): # TODO: Is there a windows api for this? domain = '.' if '@' in username: username, domain = username.split('@') if '\\' in username: domain, username = username.split('\\') return username, domain def runas(cmdLine, username, password=None, cwd=None): ''' Run a command as another user. If the process is running as an admin or system account this method does not require a password. Other non privileged accounts need to provide a password for the user to runas. Commands are run in with the highest level privileges possible for the account provided. ''' # Elevate the token from the current process access = ( win32security.TOKEN_QUERY | win32security.TOKEN_ADJUST_PRIVILEGES ) th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), access) salt.platform.win.elevate_token(th) # Try to impersonate the SYSTEM user. This process needs to be running as a # user who as been granted the SeImpersonatePrivilege, Administrator # accounts have this permission by default. try: impersonation_token = salt.platform.win.impersonate_sid( salt.platform.win.SYSTEM_SID, session_id=0, privs=['SeTcbPrivilege'], ) except WindowsError: # pylint: disable=undefined-variable log.debug("Unable to impersonate SYSTEM user") impersonation_token = None # Impersonation of the SYSTEM user failed. Fallback to an un-privileged # runas. if not impersonation_token: log.debug("No impersonation token, using unprivileged runas") return runas_unpriv(cmdLine, username, password, cwd) username, domain = split_username(username) # Validate the domain and sid exist for the username try: _, domain, _ = win32security.LookupAccountName(domain, username) except pywintypes.error as exc: message = win32api.FormatMessage(exc.winerror).rstrip('\n') raise CommandExecutionError(message) if domain == 'NT AUTHORITY': # Logon as a system level account, SYSTEM, LOCAL SERVICE, or NETWORK # SERVICE. logonType = win32con.LOGON32_LOGON_SERVICE user_token = win32security.LogonUser( username, domain, '', win32con.LOGON32_LOGON_SERVICE, win32con.LOGON32_PROVIDER_DEFAULT, ) elif password: # Login with a password. user_token = win32security.LogonUser( username, domain, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT, ) else: # Login without a password. This always returns an elevated token. user_token = salt.platform.win.logon_msv1_s4u(username).Token # Get a linked user token to elevate if needed elevation_type = win32security.GetTokenInformation( user_token, win32security.TokenElevationType ) if elevation_type > 1: user_token = win32security.GetTokenInformation( user_token, win32security.TokenLinkedToken ) # Elevate the user token salt.platform.win.elevate_token(user_token) # Make sure the user's token has access to a windows station and desktop salt.platform.win.grant_winsta_and_desktop(user_token) # Create pipes for standard in, out and error streams security_attributes = win32security.SECURITY_ATTRIBUTES() security_attributes.bInheritHandle = 1 stdin_read, stdin_write = win32pipe.CreatePipe(security_attributes, 0) stdin_read = salt.platform.win.make_inheritable(stdin_read) stdout_read, stdout_write = win32pipe.CreatePipe(security_attributes, 0) stdout_write = salt.platform.win.make_inheritable(stdout_write) stderr_read, stderr_write = win32pipe.CreatePipe(security_attributes, 0) stderr_write = salt.platform.win.make_inheritable(stderr_write) # Run the process without showing a window. creationflags = ( win32process.CREATE_NO_WINDOW | win32process.CREATE_NEW_CONSOLE | win32process.CREATE_SUSPENDED ) startup_info = salt.platform.win.STARTUPINFO( dwFlags=win32con.STARTF_USESTDHANDLES, hStdInput=stdin_read.handle, hStdOutput=stdout_write.handle, hStdError=stderr_write.handle, ) # Create the environment for the user env = win32profile.CreateEnvironmentBlock(user_token, False) # Start the process in a suspended state. process_info = salt.platform.win.CreateProcessWithTokenW( int(user_token), logonflags=1, applicationname=None, commandline=cmdLine, currentdirectory=cwd, creationflags=creationflags, startupinfo=startup_info, environment=env, ) hProcess = process_info.hProcess hThread = process_info.hThread dwProcessId = process_info.dwProcessId dwThreadId = process_info.dwThreadId salt.platform.win.kernel32.CloseHandle(stdin_write.handle) salt.platform.win.kernel32.CloseHandle(stdout_write.handle) salt.platform.win.kernel32.CloseHandle(stderr_write.handle) ret = {'pid': dwProcessId} # Resume the process psutil.Process(dwProcessId).resume() # Wait for the process to exit and get it's return code. if win32event.WaitForSingleObject(hProcess, win32event.INFINITE) == win32con.WAIT_OBJECT_0: exitcode = win32process.GetExitCodeProcess(hProcess) ret['retcode'] = exitcode # Read standard out fd_out = msvcrt.open_osfhandle(stdout_read.handle, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_out, 'r') as f_out: stdout = f_out.read() ret['stdout'] = stdout # Read standard error fd_err = msvcrt.open_osfhandle(stderr_read.handle, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_err, 'r') as f_err: stderr = f_err.read() ret['stderr'] = stderr salt.platform.win.kernel32.CloseHandle(hProcess) win32api.CloseHandle(user_token) if impersonation_token: win32security.RevertToSelf() win32api.CloseHandle(impersonation_token) return ret
saltstack/salt
salt/matchers/data_match.py
match
python
def match(tgt, functions=None, opts=None): ''' Match based on the local data store on the minion ''' if not opts: opts = __opts__ if functions is None: utils = salt.loader.utils(opts) functions = salt.loader.minion_mods(opts, utils=utils) comps = tgt.split(':') if len(comps) < 2: return False val = functions['data.getval'](comps[0]) if val is None: # The value is not defined return False if isinstance(val, list): # We are matching a single component to a single list member for member in val: if fnmatch.fnmatch(six.text_type(member).lower(), comps[1].lower()): return True return False if isinstance(val, dict): if comps[1] in val: return True return False return bool(fnmatch.fnmatch( val, comps[1], ))
Match based on the local data store on the minion
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/data_match.py#L19-L48
null
# -*- coding: utf-8 -*- ''' This is the default data matcher. ''' from __future__ import absolute_import, print_function, unicode_literals import fnmatch import logging from salt.ext import six # pylint: disable=3rd-party-module-not-gated import salt.utils.data # pylint: disable=3rd-party-module-not-gated import salt.utils.minions # pylint: disable=3rd-party-module-not-gated import salt.utils.network # pylint: disable=3rd-party-module-not-gated import salt.loader # pylint: disable=3rd-party-module-not-gated log = logging.getLogger(__name__)
saltstack/salt
salt/states/glance.py
_find_image
python
def _find_image(name): ''' Tries to find image with given name, returns - image, 'Found image <name>' - None, 'No such image found' - False, 'Found more than one image with given name' ''' try: images = __salt__['glance.image_list'](name=name) except kstone_Unauthorized: return False, 'keystoneclient: Unauthorized' except glance_Unauthorized: return False, 'glanceclient: Unauthorized' log.debug('Got images: %s', images) if type(images) is dict and len(images) == 1 and 'images' in images: images = images['images'] images_list = images.values() if type(images) is dict else images if not images_list: return None, 'No image with name "{0}"'.format(name) elif len(images_list) == 1: return images_list[0], 'Found image {0}'.format(name) elif len(images_list) > 1: return False, 'Found more than one image with given name' else: raise NotImplementedError
Tries to find image with given name, returns - image, 'Found image <name>' - None, 'No such image found' - False, 'Found more than one image with given name'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glance.py#L43-L70
null
# -*- coding: utf-8 -*- ''' Managing Images in OpenStack Glance =================================== ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs # Import OpenStack libs try: from keystoneclient.exceptions import \ Unauthorized as kstone_Unauthorized HAS_KEYSTONE = True except ImportError: try: from keystoneclient.apiclient.exceptions import \ Unauthorized as kstone_Unauthorized HAS_KEYSTONE = True except ImportError: HAS_KEYSTONE = False try: from glanceclient.exc import \ HTTPUnauthorized as glance_Unauthorized HAS_GLANCE = True except ImportError: HAS_GLANCE = False log = logging.getLogger(__name__) def __virtual__(): ''' Only load if dependencies are loaded ''' return HAS_KEYSTONE and HAS_GLANCE def image_present(name, visibility='public', protected=None, checksum=None, location=None, disk_format='raw', wait_for=None, timeout=30): ''' Checks if given image is present with properties set as specified. An image should got through the stages 'queued', 'saving' before becoming 'active'. The attribute 'checksum' can only be checked once the image is active. If you don't specify 'wait_for' but 'checksum' the function will wait for the image to become active before comparing checksums. If you don't specify checksum either the function will return when the image reached 'saving'. The default timeout for both is 30 seconds. Supported properties: - visibility ('public' or 'private') - protected (bool) - checksum (string, md5sum) - location (URL, to copy from) - disk_format ('raw' (default), 'vhd', 'vhdx', 'vmdk', 'vdi', 'iso', 'qcow2', 'aki', 'ari' or 'ami') ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': '', } acceptable = ['queued', 'saving', 'active'] if wait_for is None and checksum is None: wait_for = 'saving' elif wait_for is None and checksum is not None: wait_for = 'active' # Just pop states until we reach the # first acceptable one: while len(acceptable) > 1: if acceptable[0] == wait_for: break else: acceptable.pop(0) image, msg = _find_image(name) if image is False: if __opts__['test']: ret['result'] = None else: ret['result'] = False ret['comment'] = msg return ret log.debug(msg) # No image yet and we know where to get one if image is None and location is not None: if __opts__['test']: ret['result'] = None ret['comment'] = 'glance.image_present would ' \ 'create an image from {0}'.format(location) return ret image = __salt__['glance.image_create'](name=name, protected=protected, visibility=visibility, location=location, disk_format=disk_format) log.debug('Created new image:\n%s', image) ret['changes'] = { name: { 'new': { 'id': image['id'] }, 'old': None } } timer = timeout # Kinda busy-loopy but I don't think the Glance # API has events we can listen for while timer > 0: if 'status' in image and \ image['status'] in acceptable: log.debug('Image %s has reached status %s', image['name'], image['status']) break else: timer -= 5 time.sleep(5) image, msg = _find_image(name) if not image: ret['result'] = False ret['comment'] += 'Created image {0} '.format( name) + ' vanished:\n' + msg return ret if timer <= 0 and image['status'] not in acceptable: ret['result'] = False ret['comment'] += 'Image didn\'t reach an acceptable '+\ 'state ({0}) before timeout:\n'.format(acceptable)+\ '\tLast status was "{0}".\n'.format(image['status']) # There's no image but where would I get one?? elif location is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'No location to copy image from specified,\n' +\ 'glance.image_present would not create one' else: ret['result'] = False ret['comment'] = 'No location to copy image from specified,\n' +\ 'not creating a new image.' return ret # If we've created a new image also return its last status: if name in ret['changes']: ret['changes'][name]['new']['status'] = image['status'] if visibility: if image['visibility'] != visibility: old_value = image['visibility'] if not __opts__['test']: image = __salt__['glance.image_update']( id=image['id'], visibility=visibility) # Check if image_update() worked: if image['visibility'] != visibility: if not __opts__['test']: ret['result'] = False elif __opts__['test']: ret['result'] = None ret['comment'] += '"visibility" is {0}, '\ 'should be {1}.\n'.format(image['visibility'], visibility) else: if 'new' in ret['changes']: ret['changes']['new']['visibility'] = visibility else: ret['changes']['new'] = {'visibility': visibility} if 'old' in ret['changes']: ret['changes']['old']['visibility'] = old_value else: ret['changes']['old'] = {'visibility': old_value} else: ret['comment'] += '"visibility" is correct ({0}).\n'.format( visibility) if protected is not None: if not isinstance(protected, bool) or image['protected'] ^ protected: if not __opts__['test']: ret['result'] = False else: ret['result'] = None ret['comment'] += '"protected" is {0}, should be {1}.\n'.format( image['protected'], protected) else: ret['comment'] += '"protected" is correct ({0}).\n'.format( protected) if 'status' in image and checksum: if image['status'] == 'active': if 'checksum' not in image: # Refresh our info about the image image = __salt__['glance.image_show'](image['id']) if 'checksum' not in image: if not __opts__['test']: ret['result'] = False else: ret['result'] = None ret['comment'] += 'No checksum available for this image:\n' +\ '\tImage has status "{0}".'.format(image['status']) elif image['checksum'] != checksum: if not __opts__['test']: ret['result'] = False else: ret['result'] = None ret['comment'] += '"checksum" is {0}, should be {1}.\n'.format( image['checksum'], checksum) else: ret['comment'] += '"checksum" is correct ({0}).\n'.format( checksum) elif image['status'] in ['saving', 'queued']: ret['comment'] += 'Checksum won\'t be verified as image ' +\ 'hasn\'t reached\n\t "status=active" yet.\n' log.debug('glance.image_present will return: %s', ret) return ret
saltstack/salt
salt/states/glance.py
image_present
python
def image_present(name, visibility='public', protected=None, checksum=None, location=None, disk_format='raw', wait_for=None, timeout=30): ''' Checks if given image is present with properties set as specified. An image should got through the stages 'queued', 'saving' before becoming 'active'. The attribute 'checksum' can only be checked once the image is active. If you don't specify 'wait_for' but 'checksum' the function will wait for the image to become active before comparing checksums. If you don't specify checksum either the function will return when the image reached 'saving'. The default timeout for both is 30 seconds. Supported properties: - visibility ('public' or 'private') - protected (bool) - checksum (string, md5sum) - location (URL, to copy from) - disk_format ('raw' (default), 'vhd', 'vhdx', 'vmdk', 'vdi', 'iso', 'qcow2', 'aki', 'ari' or 'ami') ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': '', } acceptable = ['queued', 'saving', 'active'] if wait_for is None and checksum is None: wait_for = 'saving' elif wait_for is None and checksum is not None: wait_for = 'active' # Just pop states until we reach the # first acceptable one: while len(acceptable) > 1: if acceptable[0] == wait_for: break else: acceptable.pop(0) image, msg = _find_image(name) if image is False: if __opts__['test']: ret['result'] = None else: ret['result'] = False ret['comment'] = msg return ret log.debug(msg) # No image yet and we know where to get one if image is None and location is not None: if __opts__['test']: ret['result'] = None ret['comment'] = 'glance.image_present would ' \ 'create an image from {0}'.format(location) return ret image = __salt__['glance.image_create'](name=name, protected=protected, visibility=visibility, location=location, disk_format=disk_format) log.debug('Created new image:\n%s', image) ret['changes'] = { name: { 'new': { 'id': image['id'] }, 'old': None } } timer = timeout # Kinda busy-loopy but I don't think the Glance # API has events we can listen for while timer > 0: if 'status' in image and \ image['status'] in acceptable: log.debug('Image %s has reached status %s', image['name'], image['status']) break else: timer -= 5 time.sleep(5) image, msg = _find_image(name) if not image: ret['result'] = False ret['comment'] += 'Created image {0} '.format( name) + ' vanished:\n' + msg return ret if timer <= 0 and image['status'] not in acceptable: ret['result'] = False ret['comment'] += 'Image didn\'t reach an acceptable '+\ 'state ({0}) before timeout:\n'.format(acceptable)+\ '\tLast status was "{0}".\n'.format(image['status']) # There's no image but where would I get one?? elif location is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'No location to copy image from specified,\n' +\ 'glance.image_present would not create one' else: ret['result'] = False ret['comment'] = 'No location to copy image from specified,\n' +\ 'not creating a new image.' return ret # If we've created a new image also return its last status: if name in ret['changes']: ret['changes'][name]['new']['status'] = image['status'] if visibility: if image['visibility'] != visibility: old_value = image['visibility'] if not __opts__['test']: image = __salt__['glance.image_update']( id=image['id'], visibility=visibility) # Check if image_update() worked: if image['visibility'] != visibility: if not __opts__['test']: ret['result'] = False elif __opts__['test']: ret['result'] = None ret['comment'] += '"visibility" is {0}, '\ 'should be {1}.\n'.format(image['visibility'], visibility) else: if 'new' in ret['changes']: ret['changes']['new']['visibility'] = visibility else: ret['changes']['new'] = {'visibility': visibility} if 'old' in ret['changes']: ret['changes']['old']['visibility'] = old_value else: ret['changes']['old'] = {'visibility': old_value} else: ret['comment'] += '"visibility" is correct ({0}).\n'.format( visibility) if protected is not None: if not isinstance(protected, bool) or image['protected'] ^ protected: if not __opts__['test']: ret['result'] = False else: ret['result'] = None ret['comment'] += '"protected" is {0}, should be {1}.\n'.format( image['protected'], protected) else: ret['comment'] += '"protected" is correct ({0}).\n'.format( protected) if 'status' in image and checksum: if image['status'] == 'active': if 'checksum' not in image: # Refresh our info about the image image = __salt__['glance.image_show'](image['id']) if 'checksum' not in image: if not __opts__['test']: ret['result'] = False else: ret['result'] = None ret['comment'] += 'No checksum available for this image:\n' +\ '\tImage has status "{0}".'.format(image['status']) elif image['checksum'] != checksum: if not __opts__['test']: ret['result'] = False else: ret['result'] = None ret['comment'] += '"checksum" is {0}, should be {1}.\n'.format( image['checksum'], checksum) else: ret['comment'] += '"checksum" is correct ({0}).\n'.format( checksum) elif image['status'] in ['saving', 'queued']: ret['comment'] += 'Checksum won\'t be verified as image ' +\ 'hasn\'t reached\n\t "status=active" yet.\n' log.debug('glance.image_present will return: %s', ret) return ret
Checks if given image is present with properties set as specified. An image should got through the stages 'queued', 'saving' before becoming 'active'. The attribute 'checksum' can only be checked once the image is active. If you don't specify 'wait_for' but 'checksum' the function will wait for the image to become active before comparing checksums. If you don't specify checksum either the function will return when the image reached 'saving'. The default timeout for both is 30 seconds. Supported properties: - visibility ('public' or 'private') - protected (bool) - checksum (string, md5sum) - location (URL, to copy from) - disk_format ('raw' (default), 'vhd', 'vhdx', 'vmdk', 'vdi', 'iso', 'qcow2', 'aki', 'ari' or 'ami')
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glance.py#L73-L250
[ "def _find_image(name):\n '''\n Tries to find image with given name, returns\n - image, 'Found image <name>'\n - None, 'No such image found'\n - False, 'Found more than one image with given name'\n '''\n try:\n images = __salt__['glance.image_list'](name=name)\n except kstone_Unauthorized:\n return False, 'keystoneclient: Unauthorized'\n except glance_Unauthorized:\n return False, 'glanceclient: Unauthorized'\n log.debug('Got images: %s', images)\n\n if type(images) is dict and len(images) == 1 and 'images' in images:\n images = images['images']\n\n images_list = images.values() if type(images) is dict else images\n\n if not images_list:\n return None, 'No image with name \"{0}\"'.format(name)\n elif len(images_list) == 1:\n return images_list[0], 'Found image {0}'.format(name)\n elif len(images_list) > 1:\n return False, 'Found more than one image with given name'\n else:\n raise NotImplementedError\n" ]
# -*- coding: utf-8 -*- ''' Managing Images in OpenStack Glance =================================== ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs # Import OpenStack libs try: from keystoneclient.exceptions import \ Unauthorized as kstone_Unauthorized HAS_KEYSTONE = True except ImportError: try: from keystoneclient.apiclient.exceptions import \ Unauthorized as kstone_Unauthorized HAS_KEYSTONE = True except ImportError: HAS_KEYSTONE = False try: from glanceclient.exc import \ HTTPUnauthorized as glance_Unauthorized HAS_GLANCE = True except ImportError: HAS_GLANCE = False log = logging.getLogger(__name__) def __virtual__(): ''' Only load if dependencies are loaded ''' return HAS_KEYSTONE and HAS_GLANCE def _find_image(name): ''' Tries to find image with given name, returns - image, 'Found image <name>' - None, 'No such image found' - False, 'Found more than one image with given name' ''' try: images = __salt__['glance.image_list'](name=name) except kstone_Unauthorized: return False, 'keystoneclient: Unauthorized' except glance_Unauthorized: return False, 'glanceclient: Unauthorized' log.debug('Got images: %s', images) if type(images) is dict and len(images) == 1 and 'images' in images: images = images['images'] images_list = images.values() if type(images) is dict else images if not images_list: return None, 'No image with name "{0}"'.format(name) elif len(images_list) == 1: return images_list[0], 'Found image {0}'.format(name) elif len(images_list) > 1: return False, 'Found more than one image with given name' else: raise NotImplementedError
saltstack/salt
salt/returners/cassandra_cql_return.py
returner
python
def returner(ret): ''' Return data to one of potentially many clustered cassandra nodes ''' query = '''INSERT INTO {keyspace}.salt_returns ( jid, minion_id, fun, alter_time, full_ret, return, success ) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['jid']), '{0}'.format(ret['id']), '{0}'.format(ret['fun']), int(time.time() * 1000), salt.utils.json.dumps(ret).replace("'", "''"), salt.utils.json.dumps(ret['return']).replace("'", "''"), ret.get('success', False)] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_return', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not insert into salt_returns with Cassandra returner.') raise except Exception as e: log.critical('Unexpected error while inserting into salt_returns: %s', e) raise # Store the last function called by the minion # The data in salt.minions will be used by get_fun and get_minions query = '''INSERT INTO {keyspace}.minions ( minion_id, last_fun ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_minion', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not store minion ID with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting minion ID into the minions ' 'table: %s', e ) raise
Return data to one of potentially many clustered cassandra nodes
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L192-L243
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\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 orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_keyspace():\n '''\n Return keyspace if it is specified at opts, if not, use default keyspace 'salt'.\n '''\n return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt')\n" ]
# -*- coding: utf-8 -*- ''' Return data to a cassandra server .. versionadded:: 2015.5.0 :maintainer: Corin Kochenower<ckochenower@saltstack.com> :maturity: new as of 2015.2 :depends: salt.modules.cassandra_cql :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :platform: all :configuration: To enable this returner, the minion will need the DataStax Python Driver for Apache Cassandra ( https://github.com/datastax/python-driver ) installed and the following values configured in the minion or master config. The list of cluster IPs must include at least one cassandra node IP address. No assumption or default will be used for the cluster IPs. The cluster IPs will be tried in the order listed. The port, username, and password values shown below will be the assumed defaults if you do not provide values.: .. code-block:: yaml cassandra: cluster: - 192.168.50.11 - 192.168.50.12 - 192.168.50.13 port: 9042 username: salt password: salt keyspace: salt Use the following cassandra database schema: .. code-block:: text CREATE KEYSPACE IF NOT EXISTS salt WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}; CREATE USER IF NOT EXISTS salt WITH PASSWORD 'salt' NOSUPERUSER; GRANT ALL ON KEYSPACE salt TO salt; USE salt; CREATE TABLE IF NOT EXISTS salt.salt_returns ( jid text, minion_id text, fun text, alter_time timestamp, full_ret text, return text, success boolean, PRIMARY KEY (jid, minion_id, fun) ) WITH CLUSTERING ORDER BY (minion_id ASC, fun ASC); CREATE INDEX IF NOT EXISTS salt_returns_minion_id ON salt.salt_returns (minion_id); CREATE INDEX IF NOT EXISTS salt_returns_fun ON salt.salt_returns (fun); CREATE TABLE IF NOT EXISTS salt.jids ( jid text PRIMARY KEY, load text ); CREATE TABLE IF NOT EXISTS salt.minions ( minion_id text PRIMARY KEY, last_fun text ); CREATE INDEX IF NOT EXISTS minions_last_fun ON salt.minions (last_fun); CREATE TABLE IF NOT EXISTS salt.salt_events ( id timeuuid, tag text, alter_time timestamp, data text, master_id text, PRIMARY KEY (id, tag) ) WITH CLUSTERING ORDER BY (tag ASC); CREATE INDEX tag ON salt.salt_events (tag); Required python modules: cassandra-driver To use the cassandra returner, append '--return cassandra_cql' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return_cql cassandra Note: if your Cassandra instance has not been tuned much you may benefit from altering some timeouts in `cassandra.yaml` like so: .. code-block:: yaml # How long the coordinator should wait for read operations to complete read_request_timeout_in_ms: 5000 # How long the coordinator should wait for seq or index scans to complete range_request_timeout_in_ms: 20000 # How long the coordinator should wait for writes to complete write_request_timeout_in_ms: 20000 # How long the coordinator should wait for counter writes to complete counter_write_request_timeout_in_ms: 10000 # How long a coordinator should continue to retry a CAS operation # that contends with other proposals for the same row cas_contention_timeout_in_ms: 5000 # How long the coordinator should wait for truncates to complete # (This can be much longer, because unless auto_snapshot is disabled # we need to flush first so we can snapshot before removing the data.) truncate_request_timeout_in_ms: 60000 # The default timeout for other, miscellaneous operations request_timeout_in_ms: 20000 As always, your mileage may vary and your Cassandra cluster may have different needs. SaltStack has seen situations where these timeouts can resolve some stacktraces that appear to come from the Datastax Python driver. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import uuid import time # Import salt libs import salt.returners import salt.utils.jid import salt.utils.json import salt.exceptions from salt.exceptions import CommandExecutionError from salt.ext import six # Import third party libs try: # The following imports are not directly required by this module. Rather, # they are required by the modules/cassandra_cql execution module, on which # this module depends. # # This returner cross-calls the cassandra_cql execution module using the __salt__ dunder. # # The modules/cassandra_cql execution module will not load if the DataStax Python Driver # for Apache Cassandra is not installed. # # This module will try to load all of the 3rd party dependencies on which the # modules/cassandra_cql execution module depends. # # Effectively, if the DataStax Python Driver for Apache Cassandra is not # installed, both the modules/cassandra_cql execution module and this returner module # will not be loaded by Salt's loader system. # pylint: disable=unused-import from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, ConnectionShutdown from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=unused-import HAS_CASSANDRA_DRIVER = True except ImportError as e: HAS_CASSANDRA_DRIVER = False log = logging.getLogger(__name__) # Define the module's virtual name # # The 'cassandra' __virtualname__ is already taken by the # returners/cassandra_return module, which utilizes nodetool. This module # cross-calls the modules/cassandra_cql execution module, which uses the # DataStax Python Driver for Apache Cassandra. Namespacing allows both the # modules/cassandra_cql and returners/cassandra_cql modules to use the # virtualname 'cassandra_cql'. __virtualname__ = 'cassandra_cql' def __virtual__(): if not HAS_CASSANDRA_DRIVER: return False, 'Could not import cassandra_cql returner; ' \ 'cassandra-driver is not installed.' return True def _get_keyspace(): ''' Return keyspace if it is specified at opts, if not, use default keyspace 'salt'. ''' return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt') def event_return(events): ''' Return event to one of potentially many clustered cassandra nodes Requires that configuration be enabled via 'event_return' option in master config. Cassandra does not support an auto-increment feature due to the highly inefficient nature of creating a monotonically increasing number across all nodes in a distributed database. Each event will be assigned a uuid by the connecting client. ''' for event in events: tag = event.get('tag', '') data = event.get('data', '') query = '''INSERT INTO {keyspace}.salt_events ( id, alter_time, data, master_id, tag ) VALUES ( ?, ?, ?, ?, ?) '''.format(keyspace=_get_keyspace()) statement_arguments = [six.text_type(uuid.uuid1()), int(time.time() * 1000), salt.utils.json.dumps(data).replace("'", "''"), __opts__['id'], tag] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not store events with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting into salt_events: %s', e) raise def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' # Load is being stored as a text datatype. Single quotes are used in the # VALUES list. Therefore, all single quotes contained in the results from # salt.utils.json.dumps(load) must be escaped Cassandra style. query = '''INSERT INTO {keyspace}.jids ( jid, load ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = [ jid, salt.utils.json.dumps(load).replace("'", "''") ] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not save load in jids table.') raise except Exception as e: log.critical('Unexpected error while inserting into jids: %s', e) raise def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass # salt-run jobs.list_jobs FAILED def get_load(jid): ''' Return the load data that marks a specified jid ''' query = '''SELECT load FROM {keyspace}.jids WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_load', [jid]) if data: load = data[0].get('load') if load: ret = salt.utils.json.loads(load) except CommandExecutionError: log.critical('Could not get load from jids table.') raise except Exception as e: log.critical('Unexpected error while getting load from jids: %s', e) raise return ret # salt-call ret.get_jid cassandra_cql 20150327234537907315 PASSED def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if minion and full_ret: ret[minion] = salt.utils.json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical( 'Unexpected error while getting job specific information: %s', e) raise return ret # salt-call ret.get_fun cassandra_cql test.ping PASSED def get_fun(fun): ''' Return a dict of the last function called for all minions ''' query = '''SELECT minion_id, last_fun FROM {keyspace}.minions WHERE last_fun = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun]) if data: for row in data: minion = row.get('minion_id') last_fun = row.get('last_fun') if minion and last_fun: ret[minion] = last_fun except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret # salt-call ret.get_jids cassandra_cql PASSED def get_jids(): ''' Return a list of all job ids ''' query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: jid = row.get('jid') load = row.get('load') if jid and load: ret[jid] = salt.utils.jid.format_jid_instance( jid, salt.utils.json.loads(load)) except CommandExecutionError: log.critical('Could not get a list of all job ids.') raise except Exception as e: log.critical( 'Unexpected error while getting list of all job ids: %s', e) raise return ret # salt-call ret.get_minions cassandra_cql PASSED def get_minions(): ''' Return a list of minions ''' query = '''SELECT DISTINCT minion_id FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace()) ret = [] # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: minion = row.get('minion_id') if minion: ret.append(minion) except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret def prep_jid(nocache, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
saltstack/salt
salt/returners/cassandra_cql_return.py
event_return
python
def event_return(events): ''' Return event to one of potentially many clustered cassandra nodes Requires that configuration be enabled via 'event_return' option in master config. Cassandra does not support an auto-increment feature due to the highly inefficient nature of creating a monotonically increasing number across all nodes in a distributed database. Each event will be assigned a uuid by the connecting client. ''' for event in events: tag = event.get('tag', '') data = event.get('data', '') query = '''INSERT INTO {keyspace}.salt_events ( id, alter_time, data, master_id, tag ) VALUES ( ?, ?, ?, ?, ?) '''.format(keyspace=_get_keyspace()) statement_arguments = [six.text_type(uuid.uuid1()), int(time.time() * 1000), salt.utils.json.dumps(data).replace("'", "''"), __opts__['id'], tag] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not store events with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting into salt_events: %s', e) raise
Return event to one of potentially many clustered cassandra nodes Requires that configuration be enabled via 'event_return' option in master config. Cassandra does not support an auto-increment feature due to the highly inefficient nature of creating a monotonically increasing number across all nodes in a distributed database. Each event will be assigned a uuid by the connecting client.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L246-L283
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\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 orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_keyspace():\n '''\n Return keyspace if it is specified at opts, if not, use default keyspace 'salt'.\n '''\n return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt')\n" ]
# -*- coding: utf-8 -*- ''' Return data to a cassandra server .. versionadded:: 2015.5.0 :maintainer: Corin Kochenower<ckochenower@saltstack.com> :maturity: new as of 2015.2 :depends: salt.modules.cassandra_cql :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :platform: all :configuration: To enable this returner, the minion will need the DataStax Python Driver for Apache Cassandra ( https://github.com/datastax/python-driver ) installed and the following values configured in the minion or master config. The list of cluster IPs must include at least one cassandra node IP address. No assumption or default will be used for the cluster IPs. The cluster IPs will be tried in the order listed. The port, username, and password values shown below will be the assumed defaults if you do not provide values.: .. code-block:: yaml cassandra: cluster: - 192.168.50.11 - 192.168.50.12 - 192.168.50.13 port: 9042 username: salt password: salt keyspace: salt Use the following cassandra database schema: .. code-block:: text CREATE KEYSPACE IF NOT EXISTS salt WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}; CREATE USER IF NOT EXISTS salt WITH PASSWORD 'salt' NOSUPERUSER; GRANT ALL ON KEYSPACE salt TO salt; USE salt; CREATE TABLE IF NOT EXISTS salt.salt_returns ( jid text, minion_id text, fun text, alter_time timestamp, full_ret text, return text, success boolean, PRIMARY KEY (jid, minion_id, fun) ) WITH CLUSTERING ORDER BY (minion_id ASC, fun ASC); CREATE INDEX IF NOT EXISTS salt_returns_minion_id ON salt.salt_returns (minion_id); CREATE INDEX IF NOT EXISTS salt_returns_fun ON salt.salt_returns (fun); CREATE TABLE IF NOT EXISTS salt.jids ( jid text PRIMARY KEY, load text ); CREATE TABLE IF NOT EXISTS salt.minions ( minion_id text PRIMARY KEY, last_fun text ); CREATE INDEX IF NOT EXISTS minions_last_fun ON salt.minions (last_fun); CREATE TABLE IF NOT EXISTS salt.salt_events ( id timeuuid, tag text, alter_time timestamp, data text, master_id text, PRIMARY KEY (id, tag) ) WITH CLUSTERING ORDER BY (tag ASC); CREATE INDEX tag ON salt.salt_events (tag); Required python modules: cassandra-driver To use the cassandra returner, append '--return cassandra_cql' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return_cql cassandra Note: if your Cassandra instance has not been tuned much you may benefit from altering some timeouts in `cassandra.yaml` like so: .. code-block:: yaml # How long the coordinator should wait for read operations to complete read_request_timeout_in_ms: 5000 # How long the coordinator should wait for seq or index scans to complete range_request_timeout_in_ms: 20000 # How long the coordinator should wait for writes to complete write_request_timeout_in_ms: 20000 # How long the coordinator should wait for counter writes to complete counter_write_request_timeout_in_ms: 10000 # How long a coordinator should continue to retry a CAS operation # that contends with other proposals for the same row cas_contention_timeout_in_ms: 5000 # How long the coordinator should wait for truncates to complete # (This can be much longer, because unless auto_snapshot is disabled # we need to flush first so we can snapshot before removing the data.) truncate_request_timeout_in_ms: 60000 # The default timeout for other, miscellaneous operations request_timeout_in_ms: 20000 As always, your mileage may vary and your Cassandra cluster may have different needs. SaltStack has seen situations where these timeouts can resolve some stacktraces that appear to come from the Datastax Python driver. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import uuid import time # Import salt libs import salt.returners import salt.utils.jid import salt.utils.json import salt.exceptions from salt.exceptions import CommandExecutionError from salt.ext import six # Import third party libs try: # The following imports are not directly required by this module. Rather, # they are required by the modules/cassandra_cql execution module, on which # this module depends. # # This returner cross-calls the cassandra_cql execution module using the __salt__ dunder. # # The modules/cassandra_cql execution module will not load if the DataStax Python Driver # for Apache Cassandra is not installed. # # This module will try to load all of the 3rd party dependencies on which the # modules/cassandra_cql execution module depends. # # Effectively, if the DataStax Python Driver for Apache Cassandra is not # installed, both the modules/cassandra_cql execution module and this returner module # will not be loaded by Salt's loader system. # pylint: disable=unused-import from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, ConnectionShutdown from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=unused-import HAS_CASSANDRA_DRIVER = True except ImportError as e: HAS_CASSANDRA_DRIVER = False log = logging.getLogger(__name__) # Define the module's virtual name # # The 'cassandra' __virtualname__ is already taken by the # returners/cassandra_return module, which utilizes nodetool. This module # cross-calls the modules/cassandra_cql execution module, which uses the # DataStax Python Driver for Apache Cassandra. Namespacing allows both the # modules/cassandra_cql and returners/cassandra_cql modules to use the # virtualname 'cassandra_cql'. __virtualname__ = 'cassandra_cql' def __virtual__(): if not HAS_CASSANDRA_DRIVER: return False, 'Could not import cassandra_cql returner; ' \ 'cassandra-driver is not installed.' return True def _get_keyspace(): ''' Return keyspace if it is specified at opts, if not, use default keyspace 'salt'. ''' return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt') def returner(ret): ''' Return data to one of potentially many clustered cassandra nodes ''' query = '''INSERT INTO {keyspace}.salt_returns ( jid, minion_id, fun, alter_time, full_ret, return, success ) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['jid']), '{0}'.format(ret['id']), '{0}'.format(ret['fun']), int(time.time() * 1000), salt.utils.json.dumps(ret).replace("'", "''"), salt.utils.json.dumps(ret['return']).replace("'", "''"), ret.get('success', False)] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_return', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not insert into salt_returns with Cassandra returner.') raise except Exception as e: log.critical('Unexpected error while inserting into salt_returns: %s', e) raise # Store the last function called by the minion # The data in salt.minions will be used by get_fun and get_minions query = '''INSERT INTO {keyspace}.minions ( minion_id, last_fun ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_minion', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not store minion ID with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting minion ID into the minions ' 'table: %s', e ) raise def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' # Load is being stored as a text datatype. Single quotes are used in the # VALUES list. Therefore, all single quotes contained in the results from # salt.utils.json.dumps(load) must be escaped Cassandra style. query = '''INSERT INTO {keyspace}.jids ( jid, load ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = [ jid, salt.utils.json.dumps(load).replace("'", "''") ] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not save load in jids table.') raise except Exception as e: log.critical('Unexpected error while inserting into jids: %s', e) raise def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass # salt-run jobs.list_jobs FAILED def get_load(jid): ''' Return the load data that marks a specified jid ''' query = '''SELECT load FROM {keyspace}.jids WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_load', [jid]) if data: load = data[0].get('load') if load: ret = salt.utils.json.loads(load) except CommandExecutionError: log.critical('Could not get load from jids table.') raise except Exception as e: log.critical('Unexpected error while getting load from jids: %s', e) raise return ret # salt-call ret.get_jid cassandra_cql 20150327234537907315 PASSED def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if minion and full_ret: ret[minion] = salt.utils.json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical( 'Unexpected error while getting job specific information: %s', e) raise return ret # salt-call ret.get_fun cassandra_cql test.ping PASSED def get_fun(fun): ''' Return a dict of the last function called for all minions ''' query = '''SELECT minion_id, last_fun FROM {keyspace}.minions WHERE last_fun = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun]) if data: for row in data: minion = row.get('minion_id') last_fun = row.get('last_fun') if minion and last_fun: ret[minion] = last_fun except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret # salt-call ret.get_jids cassandra_cql PASSED def get_jids(): ''' Return a list of all job ids ''' query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: jid = row.get('jid') load = row.get('load') if jid and load: ret[jid] = salt.utils.jid.format_jid_instance( jid, salt.utils.json.loads(load)) except CommandExecutionError: log.critical('Could not get a list of all job ids.') raise except Exception as e: log.critical( 'Unexpected error while getting list of all job ids: %s', e) raise return ret # salt-call ret.get_minions cassandra_cql PASSED def get_minions(): ''' Return a list of minions ''' query = '''SELECT DISTINCT minion_id FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace()) ret = [] # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: minion = row.get('minion_id') if minion: ret.append(minion) except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret def prep_jid(nocache, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
saltstack/salt
salt/returners/cassandra_cql_return.py
save_load
python
def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' # Load is being stored as a text datatype. Single quotes are used in the # VALUES list. Therefore, all single quotes contained in the results from # salt.utils.json.dumps(load) must be escaped Cassandra style. query = '''INSERT INTO {keyspace}.jids ( jid, load ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = [ jid, salt.utils.json.dumps(load).replace("'", "''") ] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not save load in jids table.') raise except Exception as e: log.critical('Unexpected error while inserting into jids: %s', e) raise
Save the load to the specified jid id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L286-L312
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\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 orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_keyspace():\n '''\n Return keyspace if it is specified at opts, if not, use default keyspace 'salt'.\n '''\n return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt')\n" ]
# -*- coding: utf-8 -*- ''' Return data to a cassandra server .. versionadded:: 2015.5.0 :maintainer: Corin Kochenower<ckochenower@saltstack.com> :maturity: new as of 2015.2 :depends: salt.modules.cassandra_cql :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :platform: all :configuration: To enable this returner, the minion will need the DataStax Python Driver for Apache Cassandra ( https://github.com/datastax/python-driver ) installed and the following values configured in the minion or master config. The list of cluster IPs must include at least one cassandra node IP address. No assumption or default will be used for the cluster IPs. The cluster IPs will be tried in the order listed. The port, username, and password values shown below will be the assumed defaults if you do not provide values.: .. code-block:: yaml cassandra: cluster: - 192.168.50.11 - 192.168.50.12 - 192.168.50.13 port: 9042 username: salt password: salt keyspace: salt Use the following cassandra database schema: .. code-block:: text CREATE KEYSPACE IF NOT EXISTS salt WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}; CREATE USER IF NOT EXISTS salt WITH PASSWORD 'salt' NOSUPERUSER; GRANT ALL ON KEYSPACE salt TO salt; USE salt; CREATE TABLE IF NOT EXISTS salt.salt_returns ( jid text, minion_id text, fun text, alter_time timestamp, full_ret text, return text, success boolean, PRIMARY KEY (jid, minion_id, fun) ) WITH CLUSTERING ORDER BY (minion_id ASC, fun ASC); CREATE INDEX IF NOT EXISTS salt_returns_minion_id ON salt.salt_returns (minion_id); CREATE INDEX IF NOT EXISTS salt_returns_fun ON salt.salt_returns (fun); CREATE TABLE IF NOT EXISTS salt.jids ( jid text PRIMARY KEY, load text ); CREATE TABLE IF NOT EXISTS salt.minions ( minion_id text PRIMARY KEY, last_fun text ); CREATE INDEX IF NOT EXISTS minions_last_fun ON salt.minions (last_fun); CREATE TABLE IF NOT EXISTS salt.salt_events ( id timeuuid, tag text, alter_time timestamp, data text, master_id text, PRIMARY KEY (id, tag) ) WITH CLUSTERING ORDER BY (tag ASC); CREATE INDEX tag ON salt.salt_events (tag); Required python modules: cassandra-driver To use the cassandra returner, append '--return cassandra_cql' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return_cql cassandra Note: if your Cassandra instance has not been tuned much you may benefit from altering some timeouts in `cassandra.yaml` like so: .. code-block:: yaml # How long the coordinator should wait for read operations to complete read_request_timeout_in_ms: 5000 # How long the coordinator should wait for seq or index scans to complete range_request_timeout_in_ms: 20000 # How long the coordinator should wait for writes to complete write_request_timeout_in_ms: 20000 # How long the coordinator should wait for counter writes to complete counter_write_request_timeout_in_ms: 10000 # How long a coordinator should continue to retry a CAS operation # that contends with other proposals for the same row cas_contention_timeout_in_ms: 5000 # How long the coordinator should wait for truncates to complete # (This can be much longer, because unless auto_snapshot is disabled # we need to flush first so we can snapshot before removing the data.) truncate_request_timeout_in_ms: 60000 # The default timeout for other, miscellaneous operations request_timeout_in_ms: 20000 As always, your mileage may vary and your Cassandra cluster may have different needs. SaltStack has seen situations where these timeouts can resolve some stacktraces that appear to come from the Datastax Python driver. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import uuid import time # Import salt libs import salt.returners import salt.utils.jid import salt.utils.json import salt.exceptions from salt.exceptions import CommandExecutionError from salt.ext import six # Import third party libs try: # The following imports are not directly required by this module. Rather, # they are required by the modules/cassandra_cql execution module, on which # this module depends. # # This returner cross-calls the cassandra_cql execution module using the __salt__ dunder. # # The modules/cassandra_cql execution module will not load if the DataStax Python Driver # for Apache Cassandra is not installed. # # This module will try to load all of the 3rd party dependencies on which the # modules/cassandra_cql execution module depends. # # Effectively, if the DataStax Python Driver for Apache Cassandra is not # installed, both the modules/cassandra_cql execution module and this returner module # will not be loaded by Salt's loader system. # pylint: disable=unused-import from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, ConnectionShutdown from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=unused-import HAS_CASSANDRA_DRIVER = True except ImportError as e: HAS_CASSANDRA_DRIVER = False log = logging.getLogger(__name__) # Define the module's virtual name # # The 'cassandra' __virtualname__ is already taken by the # returners/cassandra_return module, which utilizes nodetool. This module # cross-calls the modules/cassandra_cql execution module, which uses the # DataStax Python Driver for Apache Cassandra. Namespacing allows both the # modules/cassandra_cql and returners/cassandra_cql modules to use the # virtualname 'cassandra_cql'. __virtualname__ = 'cassandra_cql' def __virtual__(): if not HAS_CASSANDRA_DRIVER: return False, 'Could not import cassandra_cql returner; ' \ 'cassandra-driver is not installed.' return True def _get_keyspace(): ''' Return keyspace if it is specified at opts, if not, use default keyspace 'salt'. ''' return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt') def returner(ret): ''' Return data to one of potentially many clustered cassandra nodes ''' query = '''INSERT INTO {keyspace}.salt_returns ( jid, minion_id, fun, alter_time, full_ret, return, success ) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['jid']), '{0}'.format(ret['id']), '{0}'.format(ret['fun']), int(time.time() * 1000), salt.utils.json.dumps(ret).replace("'", "''"), salt.utils.json.dumps(ret['return']).replace("'", "''"), ret.get('success', False)] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_return', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not insert into salt_returns with Cassandra returner.') raise except Exception as e: log.critical('Unexpected error while inserting into salt_returns: %s', e) raise # Store the last function called by the minion # The data in salt.minions will be used by get_fun and get_minions query = '''INSERT INTO {keyspace}.minions ( minion_id, last_fun ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_minion', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not store minion ID with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting minion ID into the minions ' 'table: %s', e ) raise def event_return(events): ''' Return event to one of potentially many clustered cassandra nodes Requires that configuration be enabled via 'event_return' option in master config. Cassandra does not support an auto-increment feature due to the highly inefficient nature of creating a monotonically increasing number across all nodes in a distributed database. Each event will be assigned a uuid by the connecting client. ''' for event in events: tag = event.get('tag', '') data = event.get('data', '') query = '''INSERT INTO {keyspace}.salt_events ( id, alter_time, data, master_id, tag ) VALUES ( ?, ?, ?, ?, ?) '''.format(keyspace=_get_keyspace()) statement_arguments = [six.text_type(uuid.uuid1()), int(time.time() * 1000), salt.utils.json.dumps(data).replace("'", "''"), __opts__['id'], tag] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not store events with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting into salt_events: %s', e) raise def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass # salt-run jobs.list_jobs FAILED def get_load(jid): ''' Return the load data that marks a specified jid ''' query = '''SELECT load FROM {keyspace}.jids WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_load', [jid]) if data: load = data[0].get('load') if load: ret = salt.utils.json.loads(load) except CommandExecutionError: log.critical('Could not get load from jids table.') raise except Exception as e: log.critical('Unexpected error while getting load from jids: %s', e) raise return ret # salt-call ret.get_jid cassandra_cql 20150327234537907315 PASSED def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if minion and full_ret: ret[minion] = salt.utils.json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical( 'Unexpected error while getting job specific information: %s', e) raise return ret # salt-call ret.get_fun cassandra_cql test.ping PASSED def get_fun(fun): ''' Return a dict of the last function called for all minions ''' query = '''SELECT minion_id, last_fun FROM {keyspace}.minions WHERE last_fun = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun]) if data: for row in data: minion = row.get('minion_id') last_fun = row.get('last_fun') if minion and last_fun: ret[minion] = last_fun except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret # salt-call ret.get_jids cassandra_cql PASSED def get_jids(): ''' Return a list of all job ids ''' query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: jid = row.get('jid') load = row.get('load') if jid and load: ret[jid] = salt.utils.jid.format_jid_instance( jid, salt.utils.json.loads(load)) except CommandExecutionError: log.critical('Could not get a list of all job ids.') raise except Exception as e: log.critical( 'Unexpected error while getting list of all job ids: %s', e) raise return ret # salt-call ret.get_minions cassandra_cql PASSED def get_minions(): ''' Return a list of minions ''' query = '''SELECT DISTINCT minion_id FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace()) ret = [] # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: minion = row.get('minion_id') if minion: ret.append(minion) except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret def prep_jid(nocache, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
saltstack/salt
salt/returners/cassandra_cql_return.py
get_jid
python
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if minion and full_ret: ret[minion] = salt.utils.json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical( 'Unexpected error while getting job specific information: %s', e) raise return ret
Return the information returned when the specified job id was executed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L350-L376
[ "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", "def _get_keyspace():\n '''\n Return keyspace if it is specified at opts, if not, use default keyspace 'salt'.\n '''\n return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt')\n" ]
# -*- coding: utf-8 -*- ''' Return data to a cassandra server .. versionadded:: 2015.5.0 :maintainer: Corin Kochenower<ckochenower@saltstack.com> :maturity: new as of 2015.2 :depends: salt.modules.cassandra_cql :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :platform: all :configuration: To enable this returner, the minion will need the DataStax Python Driver for Apache Cassandra ( https://github.com/datastax/python-driver ) installed and the following values configured in the minion or master config. The list of cluster IPs must include at least one cassandra node IP address. No assumption or default will be used for the cluster IPs. The cluster IPs will be tried in the order listed. The port, username, and password values shown below will be the assumed defaults if you do not provide values.: .. code-block:: yaml cassandra: cluster: - 192.168.50.11 - 192.168.50.12 - 192.168.50.13 port: 9042 username: salt password: salt keyspace: salt Use the following cassandra database schema: .. code-block:: text CREATE KEYSPACE IF NOT EXISTS salt WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}; CREATE USER IF NOT EXISTS salt WITH PASSWORD 'salt' NOSUPERUSER; GRANT ALL ON KEYSPACE salt TO salt; USE salt; CREATE TABLE IF NOT EXISTS salt.salt_returns ( jid text, minion_id text, fun text, alter_time timestamp, full_ret text, return text, success boolean, PRIMARY KEY (jid, minion_id, fun) ) WITH CLUSTERING ORDER BY (minion_id ASC, fun ASC); CREATE INDEX IF NOT EXISTS salt_returns_minion_id ON salt.salt_returns (minion_id); CREATE INDEX IF NOT EXISTS salt_returns_fun ON salt.salt_returns (fun); CREATE TABLE IF NOT EXISTS salt.jids ( jid text PRIMARY KEY, load text ); CREATE TABLE IF NOT EXISTS salt.minions ( minion_id text PRIMARY KEY, last_fun text ); CREATE INDEX IF NOT EXISTS minions_last_fun ON salt.minions (last_fun); CREATE TABLE IF NOT EXISTS salt.salt_events ( id timeuuid, tag text, alter_time timestamp, data text, master_id text, PRIMARY KEY (id, tag) ) WITH CLUSTERING ORDER BY (tag ASC); CREATE INDEX tag ON salt.salt_events (tag); Required python modules: cassandra-driver To use the cassandra returner, append '--return cassandra_cql' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return_cql cassandra Note: if your Cassandra instance has not been tuned much you may benefit from altering some timeouts in `cassandra.yaml` like so: .. code-block:: yaml # How long the coordinator should wait for read operations to complete read_request_timeout_in_ms: 5000 # How long the coordinator should wait for seq or index scans to complete range_request_timeout_in_ms: 20000 # How long the coordinator should wait for writes to complete write_request_timeout_in_ms: 20000 # How long the coordinator should wait for counter writes to complete counter_write_request_timeout_in_ms: 10000 # How long a coordinator should continue to retry a CAS operation # that contends with other proposals for the same row cas_contention_timeout_in_ms: 5000 # How long the coordinator should wait for truncates to complete # (This can be much longer, because unless auto_snapshot is disabled # we need to flush first so we can snapshot before removing the data.) truncate_request_timeout_in_ms: 60000 # The default timeout for other, miscellaneous operations request_timeout_in_ms: 20000 As always, your mileage may vary and your Cassandra cluster may have different needs. SaltStack has seen situations where these timeouts can resolve some stacktraces that appear to come from the Datastax Python driver. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import uuid import time # Import salt libs import salt.returners import salt.utils.jid import salt.utils.json import salt.exceptions from salt.exceptions import CommandExecutionError from salt.ext import six # Import third party libs try: # The following imports are not directly required by this module. Rather, # they are required by the modules/cassandra_cql execution module, on which # this module depends. # # This returner cross-calls the cassandra_cql execution module using the __salt__ dunder. # # The modules/cassandra_cql execution module will not load if the DataStax Python Driver # for Apache Cassandra is not installed. # # This module will try to load all of the 3rd party dependencies on which the # modules/cassandra_cql execution module depends. # # Effectively, if the DataStax Python Driver for Apache Cassandra is not # installed, both the modules/cassandra_cql execution module and this returner module # will not be loaded by Salt's loader system. # pylint: disable=unused-import from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, ConnectionShutdown from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=unused-import HAS_CASSANDRA_DRIVER = True except ImportError as e: HAS_CASSANDRA_DRIVER = False log = logging.getLogger(__name__) # Define the module's virtual name # # The 'cassandra' __virtualname__ is already taken by the # returners/cassandra_return module, which utilizes nodetool. This module # cross-calls the modules/cassandra_cql execution module, which uses the # DataStax Python Driver for Apache Cassandra. Namespacing allows both the # modules/cassandra_cql and returners/cassandra_cql modules to use the # virtualname 'cassandra_cql'. __virtualname__ = 'cassandra_cql' def __virtual__(): if not HAS_CASSANDRA_DRIVER: return False, 'Could not import cassandra_cql returner; ' \ 'cassandra-driver is not installed.' return True def _get_keyspace(): ''' Return keyspace if it is specified at opts, if not, use default keyspace 'salt'. ''' return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt') def returner(ret): ''' Return data to one of potentially many clustered cassandra nodes ''' query = '''INSERT INTO {keyspace}.salt_returns ( jid, minion_id, fun, alter_time, full_ret, return, success ) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['jid']), '{0}'.format(ret['id']), '{0}'.format(ret['fun']), int(time.time() * 1000), salt.utils.json.dumps(ret).replace("'", "''"), salt.utils.json.dumps(ret['return']).replace("'", "''"), ret.get('success', False)] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_return', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not insert into salt_returns with Cassandra returner.') raise except Exception as e: log.critical('Unexpected error while inserting into salt_returns: %s', e) raise # Store the last function called by the minion # The data in salt.minions will be used by get_fun and get_minions query = '''INSERT INTO {keyspace}.minions ( minion_id, last_fun ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_minion', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not store minion ID with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting minion ID into the minions ' 'table: %s', e ) raise def event_return(events): ''' Return event to one of potentially many clustered cassandra nodes Requires that configuration be enabled via 'event_return' option in master config. Cassandra does not support an auto-increment feature due to the highly inefficient nature of creating a monotonically increasing number across all nodes in a distributed database. Each event will be assigned a uuid by the connecting client. ''' for event in events: tag = event.get('tag', '') data = event.get('data', '') query = '''INSERT INTO {keyspace}.salt_events ( id, alter_time, data, master_id, tag ) VALUES ( ?, ?, ?, ?, ?) '''.format(keyspace=_get_keyspace()) statement_arguments = [six.text_type(uuid.uuid1()), int(time.time() * 1000), salt.utils.json.dumps(data).replace("'", "''"), __opts__['id'], tag] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not store events with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting into salt_events: %s', e) raise def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' # Load is being stored as a text datatype. Single quotes are used in the # VALUES list. Therefore, all single quotes contained in the results from # salt.utils.json.dumps(load) must be escaped Cassandra style. query = '''INSERT INTO {keyspace}.jids ( jid, load ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = [ jid, salt.utils.json.dumps(load).replace("'", "''") ] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not save load in jids table.') raise except Exception as e: log.critical('Unexpected error while inserting into jids: %s', e) raise def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass # salt-run jobs.list_jobs FAILED def get_load(jid): ''' Return the load data that marks a specified jid ''' query = '''SELECT load FROM {keyspace}.jids WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_load', [jid]) if data: load = data[0].get('load') if load: ret = salt.utils.json.loads(load) except CommandExecutionError: log.critical('Could not get load from jids table.') raise except Exception as e: log.critical('Unexpected error while getting load from jids: %s', e) raise return ret # salt-call ret.get_jid cassandra_cql 20150327234537907315 PASSED # salt-call ret.get_fun cassandra_cql test.ping PASSED def get_fun(fun): ''' Return a dict of the last function called for all minions ''' query = '''SELECT minion_id, last_fun FROM {keyspace}.minions WHERE last_fun = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun]) if data: for row in data: minion = row.get('minion_id') last_fun = row.get('last_fun') if minion and last_fun: ret[minion] = last_fun except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret # salt-call ret.get_jids cassandra_cql PASSED def get_jids(): ''' Return a list of all job ids ''' query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: jid = row.get('jid') load = row.get('load') if jid and load: ret[jid] = salt.utils.jid.format_jid_instance( jid, salt.utils.json.loads(load)) except CommandExecutionError: log.critical('Could not get a list of all job ids.') raise except Exception as e: log.critical( 'Unexpected error while getting list of all job ids: %s', e) raise return ret # salt-call ret.get_minions cassandra_cql PASSED def get_minions(): ''' Return a list of minions ''' query = '''SELECT DISTINCT minion_id FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace()) ret = [] # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: minion = row.get('minion_id') if minion: ret.append(minion) except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret def prep_jid(nocache, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
saltstack/salt
salt/returners/cassandra_cql_return.py
get_fun
python
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' query = '''SELECT minion_id, last_fun FROM {keyspace}.minions WHERE last_fun = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun]) if data: for row in data: minion = row.get('minion_id') last_fun = row.get('last_fun') if minion and last_fun: ret[minion] = last_fun except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret
Return a dict of the last function called for all minions
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L380-L406
[ "def _get_keyspace():\n '''\n Return keyspace if it is specified at opts, if not, use default keyspace 'salt'.\n '''\n return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt')\n" ]
# -*- coding: utf-8 -*- ''' Return data to a cassandra server .. versionadded:: 2015.5.0 :maintainer: Corin Kochenower<ckochenower@saltstack.com> :maturity: new as of 2015.2 :depends: salt.modules.cassandra_cql :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :platform: all :configuration: To enable this returner, the minion will need the DataStax Python Driver for Apache Cassandra ( https://github.com/datastax/python-driver ) installed and the following values configured in the minion or master config. The list of cluster IPs must include at least one cassandra node IP address. No assumption or default will be used for the cluster IPs. The cluster IPs will be tried in the order listed. The port, username, and password values shown below will be the assumed defaults if you do not provide values.: .. code-block:: yaml cassandra: cluster: - 192.168.50.11 - 192.168.50.12 - 192.168.50.13 port: 9042 username: salt password: salt keyspace: salt Use the following cassandra database schema: .. code-block:: text CREATE KEYSPACE IF NOT EXISTS salt WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}; CREATE USER IF NOT EXISTS salt WITH PASSWORD 'salt' NOSUPERUSER; GRANT ALL ON KEYSPACE salt TO salt; USE salt; CREATE TABLE IF NOT EXISTS salt.salt_returns ( jid text, minion_id text, fun text, alter_time timestamp, full_ret text, return text, success boolean, PRIMARY KEY (jid, minion_id, fun) ) WITH CLUSTERING ORDER BY (minion_id ASC, fun ASC); CREATE INDEX IF NOT EXISTS salt_returns_minion_id ON salt.salt_returns (minion_id); CREATE INDEX IF NOT EXISTS salt_returns_fun ON salt.salt_returns (fun); CREATE TABLE IF NOT EXISTS salt.jids ( jid text PRIMARY KEY, load text ); CREATE TABLE IF NOT EXISTS salt.minions ( minion_id text PRIMARY KEY, last_fun text ); CREATE INDEX IF NOT EXISTS minions_last_fun ON salt.minions (last_fun); CREATE TABLE IF NOT EXISTS salt.salt_events ( id timeuuid, tag text, alter_time timestamp, data text, master_id text, PRIMARY KEY (id, tag) ) WITH CLUSTERING ORDER BY (tag ASC); CREATE INDEX tag ON salt.salt_events (tag); Required python modules: cassandra-driver To use the cassandra returner, append '--return cassandra_cql' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return_cql cassandra Note: if your Cassandra instance has not been tuned much you may benefit from altering some timeouts in `cassandra.yaml` like so: .. code-block:: yaml # How long the coordinator should wait for read operations to complete read_request_timeout_in_ms: 5000 # How long the coordinator should wait for seq or index scans to complete range_request_timeout_in_ms: 20000 # How long the coordinator should wait for writes to complete write_request_timeout_in_ms: 20000 # How long the coordinator should wait for counter writes to complete counter_write_request_timeout_in_ms: 10000 # How long a coordinator should continue to retry a CAS operation # that contends with other proposals for the same row cas_contention_timeout_in_ms: 5000 # How long the coordinator should wait for truncates to complete # (This can be much longer, because unless auto_snapshot is disabled # we need to flush first so we can snapshot before removing the data.) truncate_request_timeout_in_ms: 60000 # The default timeout for other, miscellaneous operations request_timeout_in_ms: 20000 As always, your mileage may vary and your Cassandra cluster may have different needs. SaltStack has seen situations where these timeouts can resolve some stacktraces that appear to come from the Datastax Python driver. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import uuid import time # Import salt libs import salt.returners import salt.utils.jid import salt.utils.json import salt.exceptions from salt.exceptions import CommandExecutionError from salt.ext import six # Import third party libs try: # The following imports are not directly required by this module. Rather, # they are required by the modules/cassandra_cql execution module, on which # this module depends. # # This returner cross-calls the cassandra_cql execution module using the __salt__ dunder. # # The modules/cassandra_cql execution module will not load if the DataStax Python Driver # for Apache Cassandra is not installed. # # This module will try to load all of the 3rd party dependencies on which the # modules/cassandra_cql execution module depends. # # Effectively, if the DataStax Python Driver for Apache Cassandra is not # installed, both the modules/cassandra_cql execution module and this returner module # will not be loaded by Salt's loader system. # pylint: disable=unused-import from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, ConnectionShutdown from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=unused-import HAS_CASSANDRA_DRIVER = True except ImportError as e: HAS_CASSANDRA_DRIVER = False log = logging.getLogger(__name__) # Define the module's virtual name # # The 'cassandra' __virtualname__ is already taken by the # returners/cassandra_return module, which utilizes nodetool. This module # cross-calls the modules/cassandra_cql execution module, which uses the # DataStax Python Driver for Apache Cassandra. Namespacing allows both the # modules/cassandra_cql and returners/cassandra_cql modules to use the # virtualname 'cassandra_cql'. __virtualname__ = 'cassandra_cql' def __virtual__(): if not HAS_CASSANDRA_DRIVER: return False, 'Could not import cassandra_cql returner; ' \ 'cassandra-driver is not installed.' return True def _get_keyspace(): ''' Return keyspace if it is specified at opts, if not, use default keyspace 'salt'. ''' return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt') def returner(ret): ''' Return data to one of potentially many clustered cassandra nodes ''' query = '''INSERT INTO {keyspace}.salt_returns ( jid, minion_id, fun, alter_time, full_ret, return, success ) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['jid']), '{0}'.format(ret['id']), '{0}'.format(ret['fun']), int(time.time() * 1000), salt.utils.json.dumps(ret).replace("'", "''"), salt.utils.json.dumps(ret['return']).replace("'", "''"), ret.get('success', False)] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_return', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not insert into salt_returns with Cassandra returner.') raise except Exception as e: log.critical('Unexpected error while inserting into salt_returns: %s', e) raise # Store the last function called by the minion # The data in salt.minions will be used by get_fun and get_minions query = '''INSERT INTO {keyspace}.minions ( minion_id, last_fun ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_minion', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not store minion ID with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting minion ID into the minions ' 'table: %s', e ) raise def event_return(events): ''' Return event to one of potentially many clustered cassandra nodes Requires that configuration be enabled via 'event_return' option in master config. Cassandra does not support an auto-increment feature due to the highly inefficient nature of creating a monotonically increasing number across all nodes in a distributed database. Each event will be assigned a uuid by the connecting client. ''' for event in events: tag = event.get('tag', '') data = event.get('data', '') query = '''INSERT INTO {keyspace}.salt_events ( id, alter_time, data, master_id, tag ) VALUES ( ?, ?, ?, ?, ?) '''.format(keyspace=_get_keyspace()) statement_arguments = [six.text_type(uuid.uuid1()), int(time.time() * 1000), salt.utils.json.dumps(data).replace("'", "''"), __opts__['id'], tag] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not store events with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting into salt_events: %s', e) raise def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' # Load is being stored as a text datatype. Single quotes are used in the # VALUES list. Therefore, all single quotes contained in the results from # salt.utils.json.dumps(load) must be escaped Cassandra style. query = '''INSERT INTO {keyspace}.jids ( jid, load ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = [ jid, salt.utils.json.dumps(load).replace("'", "''") ] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not save load in jids table.') raise except Exception as e: log.critical('Unexpected error while inserting into jids: %s', e) raise def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass # salt-run jobs.list_jobs FAILED def get_load(jid): ''' Return the load data that marks a specified jid ''' query = '''SELECT load FROM {keyspace}.jids WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_load', [jid]) if data: load = data[0].get('load') if load: ret = salt.utils.json.loads(load) except CommandExecutionError: log.critical('Could not get load from jids table.') raise except Exception as e: log.critical('Unexpected error while getting load from jids: %s', e) raise return ret # salt-call ret.get_jid cassandra_cql 20150327234537907315 PASSED def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if minion and full_ret: ret[minion] = salt.utils.json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical( 'Unexpected error while getting job specific information: %s', e) raise return ret # salt-call ret.get_fun cassandra_cql test.ping PASSED # salt-call ret.get_jids cassandra_cql PASSED def get_jids(): ''' Return a list of all job ids ''' query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: jid = row.get('jid') load = row.get('load') if jid and load: ret[jid] = salt.utils.jid.format_jid_instance( jid, salt.utils.json.loads(load)) except CommandExecutionError: log.critical('Could not get a list of all job ids.') raise except Exception as e: log.critical( 'Unexpected error while getting list of all job ids: %s', e) raise return ret # salt-call ret.get_minions cassandra_cql PASSED def get_minions(): ''' Return a list of minions ''' query = '''SELECT DISTINCT minion_id FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace()) ret = [] # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: minion = row.get('minion_id') if minion: ret.append(minion) except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret def prep_jid(nocache, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
saltstack/salt
salt/returners/cassandra_cql_return.py
get_jids
python
def get_jids(): ''' Return a list of all job ids ''' query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: jid = row.get('jid') load = row.get('load') if jid and load: ret[jid] = salt.utils.jid.format_jid_instance( jid, salt.utils.json.loads(load)) except CommandExecutionError: log.critical('Could not get a list of all job ids.') raise except Exception as e: log.critical( 'Unexpected error while getting list of all job ids: %s', e) raise return ret
Return a list of all job ids
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L410-L437
[ "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", "def _get_keyspace():\n '''\n Return keyspace if it is specified at opts, if not, use default keyspace 'salt'.\n '''\n return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt')\n", "def format_jid_instance(jid, job):\n '''\n Format the jid correctly\n '''\n ret = format_job_instance(job)\n ret.update({'StartTime': jid_to_time(jid)})\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Return data to a cassandra server .. versionadded:: 2015.5.0 :maintainer: Corin Kochenower<ckochenower@saltstack.com> :maturity: new as of 2015.2 :depends: salt.modules.cassandra_cql :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :platform: all :configuration: To enable this returner, the minion will need the DataStax Python Driver for Apache Cassandra ( https://github.com/datastax/python-driver ) installed and the following values configured in the minion or master config. The list of cluster IPs must include at least one cassandra node IP address. No assumption or default will be used for the cluster IPs. The cluster IPs will be tried in the order listed. The port, username, and password values shown below will be the assumed defaults if you do not provide values.: .. code-block:: yaml cassandra: cluster: - 192.168.50.11 - 192.168.50.12 - 192.168.50.13 port: 9042 username: salt password: salt keyspace: salt Use the following cassandra database schema: .. code-block:: text CREATE KEYSPACE IF NOT EXISTS salt WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}; CREATE USER IF NOT EXISTS salt WITH PASSWORD 'salt' NOSUPERUSER; GRANT ALL ON KEYSPACE salt TO salt; USE salt; CREATE TABLE IF NOT EXISTS salt.salt_returns ( jid text, minion_id text, fun text, alter_time timestamp, full_ret text, return text, success boolean, PRIMARY KEY (jid, minion_id, fun) ) WITH CLUSTERING ORDER BY (minion_id ASC, fun ASC); CREATE INDEX IF NOT EXISTS salt_returns_minion_id ON salt.salt_returns (minion_id); CREATE INDEX IF NOT EXISTS salt_returns_fun ON salt.salt_returns (fun); CREATE TABLE IF NOT EXISTS salt.jids ( jid text PRIMARY KEY, load text ); CREATE TABLE IF NOT EXISTS salt.minions ( minion_id text PRIMARY KEY, last_fun text ); CREATE INDEX IF NOT EXISTS minions_last_fun ON salt.minions (last_fun); CREATE TABLE IF NOT EXISTS salt.salt_events ( id timeuuid, tag text, alter_time timestamp, data text, master_id text, PRIMARY KEY (id, tag) ) WITH CLUSTERING ORDER BY (tag ASC); CREATE INDEX tag ON salt.salt_events (tag); Required python modules: cassandra-driver To use the cassandra returner, append '--return cassandra_cql' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return_cql cassandra Note: if your Cassandra instance has not been tuned much you may benefit from altering some timeouts in `cassandra.yaml` like so: .. code-block:: yaml # How long the coordinator should wait for read operations to complete read_request_timeout_in_ms: 5000 # How long the coordinator should wait for seq or index scans to complete range_request_timeout_in_ms: 20000 # How long the coordinator should wait for writes to complete write_request_timeout_in_ms: 20000 # How long the coordinator should wait for counter writes to complete counter_write_request_timeout_in_ms: 10000 # How long a coordinator should continue to retry a CAS operation # that contends with other proposals for the same row cas_contention_timeout_in_ms: 5000 # How long the coordinator should wait for truncates to complete # (This can be much longer, because unless auto_snapshot is disabled # we need to flush first so we can snapshot before removing the data.) truncate_request_timeout_in_ms: 60000 # The default timeout for other, miscellaneous operations request_timeout_in_ms: 20000 As always, your mileage may vary and your Cassandra cluster may have different needs. SaltStack has seen situations where these timeouts can resolve some stacktraces that appear to come from the Datastax Python driver. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import uuid import time # Import salt libs import salt.returners import salt.utils.jid import salt.utils.json import salt.exceptions from salt.exceptions import CommandExecutionError from salt.ext import six # Import third party libs try: # The following imports are not directly required by this module. Rather, # they are required by the modules/cassandra_cql execution module, on which # this module depends. # # This returner cross-calls the cassandra_cql execution module using the __salt__ dunder. # # The modules/cassandra_cql execution module will not load if the DataStax Python Driver # for Apache Cassandra is not installed. # # This module will try to load all of the 3rd party dependencies on which the # modules/cassandra_cql execution module depends. # # Effectively, if the DataStax Python Driver for Apache Cassandra is not # installed, both the modules/cassandra_cql execution module and this returner module # will not be loaded by Salt's loader system. # pylint: disable=unused-import from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, ConnectionShutdown from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=unused-import HAS_CASSANDRA_DRIVER = True except ImportError as e: HAS_CASSANDRA_DRIVER = False log = logging.getLogger(__name__) # Define the module's virtual name # # The 'cassandra' __virtualname__ is already taken by the # returners/cassandra_return module, which utilizes nodetool. This module # cross-calls the modules/cassandra_cql execution module, which uses the # DataStax Python Driver for Apache Cassandra. Namespacing allows both the # modules/cassandra_cql and returners/cassandra_cql modules to use the # virtualname 'cassandra_cql'. __virtualname__ = 'cassandra_cql' def __virtual__(): if not HAS_CASSANDRA_DRIVER: return False, 'Could not import cassandra_cql returner; ' \ 'cassandra-driver is not installed.' return True def _get_keyspace(): ''' Return keyspace if it is specified at opts, if not, use default keyspace 'salt'. ''' return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt') def returner(ret): ''' Return data to one of potentially many clustered cassandra nodes ''' query = '''INSERT INTO {keyspace}.salt_returns ( jid, minion_id, fun, alter_time, full_ret, return, success ) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['jid']), '{0}'.format(ret['id']), '{0}'.format(ret['fun']), int(time.time() * 1000), salt.utils.json.dumps(ret).replace("'", "''"), salt.utils.json.dumps(ret['return']).replace("'", "''"), ret.get('success', False)] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_return', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not insert into salt_returns with Cassandra returner.') raise except Exception as e: log.critical('Unexpected error while inserting into salt_returns: %s', e) raise # Store the last function called by the minion # The data in salt.minions will be used by get_fun and get_minions query = '''INSERT INTO {keyspace}.minions ( minion_id, last_fun ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_minion', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not store minion ID with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting minion ID into the minions ' 'table: %s', e ) raise def event_return(events): ''' Return event to one of potentially many clustered cassandra nodes Requires that configuration be enabled via 'event_return' option in master config. Cassandra does not support an auto-increment feature due to the highly inefficient nature of creating a monotonically increasing number across all nodes in a distributed database. Each event will be assigned a uuid by the connecting client. ''' for event in events: tag = event.get('tag', '') data = event.get('data', '') query = '''INSERT INTO {keyspace}.salt_events ( id, alter_time, data, master_id, tag ) VALUES ( ?, ?, ?, ?, ?) '''.format(keyspace=_get_keyspace()) statement_arguments = [six.text_type(uuid.uuid1()), int(time.time() * 1000), salt.utils.json.dumps(data).replace("'", "''"), __opts__['id'], tag] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not store events with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting into salt_events: %s', e) raise def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' # Load is being stored as a text datatype. Single quotes are used in the # VALUES list. Therefore, all single quotes contained in the results from # salt.utils.json.dumps(load) must be escaped Cassandra style. query = '''INSERT INTO {keyspace}.jids ( jid, load ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = [ jid, salt.utils.json.dumps(load).replace("'", "''") ] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not save load in jids table.') raise except Exception as e: log.critical('Unexpected error while inserting into jids: %s', e) raise def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass # salt-run jobs.list_jobs FAILED def get_load(jid): ''' Return the load data that marks a specified jid ''' query = '''SELECT load FROM {keyspace}.jids WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_load', [jid]) if data: load = data[0].get('load') if load: ret = salt.utils.json.loads(load) except CommandExecutionError: log.critical('Could not get load from jids table.') raise except Exception as e: log.critical('Unexpected error while getting load from jids: %s', e) raise return ret # salt-call ret.get_jid cassandra_cql 20150327234537907315 PASSED def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if minion and full_ret: ret[minion] = salt.utils.json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical( 'Unexpected error while getting job specific information: %s', e) raise return ret # salt-call ret.get_fun cassandra_cql test.ping PASSED def get_fun(fun): ''' Return a dict of the last function called for all minions ''' query = '''SELECT minion_id, last_fun FROM {keyspace}.minions WHERE last_fun = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun]) if data: for row in data: minion = row.get('minion_id') last_fun = row.get('last_fun') if minion and last_fun: ret[minion] = last_fun except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret # salt-call ret.get_jids cassandra_cql PASSED # salt-call ret.get_minions cassandra_cql PASSED def get_minions(): ''' Return a list of minions ''' query = '''SELECT DISTINCT minion_id FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace()) ret = [] # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: minion = row.get('minion_id') if minion: ret.append(minion) except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret def prep_jid(nocache, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
saltstack/salt
salt/returners/cassandra_cql_return.py
get_minions
python
def get_minions(): ''' Return a list of minions ''' query = '''SELECT DISTINCT minion_id FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace()) ret = [] # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: minion = row.get('minion_id') if minion: ret.append(minion) except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret
Return a list of minions
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L441-L466
[ "def _get_keyspace():\n '''\n Return keyspace if it is specified at opts, if not, use default keyspace 'salt'.\n '''\n return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt')\n" ]
# -*- coding: utf-8 -*- ''' Return data to a cassandra server .. versionadded:: 2015.5.0 :maintainer: Corin Kochenower<ckochenower@saltstack.com> :maturity: new as of 2015.2 :depends: salt.modules.cassandra_cql :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :platform: all :configuration: To enable this returner, the minion will need the DataStax Python Driver for Apache Cassandra ( https://github.com/datastax/python-driver ) installed and the following values configured in the minion or master config. The list of cluster IPs must include at least one cassandra node IP address. No assumption or default will be used for the cluster IPs. The cluster IPs will be tried in the order listed. The port, username, and password values shown below will be the assumed defaults if you do not provide values.: .. code-block:: yaml cassandra: cluster: - 192.168.50.11 - 192.168.50.12 - 192.168.50.13 port: 9042 username: salt password: salt keyspace: salt Use the following cassandra database schema: .. code-block:: text CREATE KEYSPACE IF NOT EXISTS salt WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}; CREATE USER IF NOT EXISTS salt WITH PASSWORD 'salt' NOSUPERUSER; GRANT ALL ON KEYSPACE salt TO salt; USE salt; CREATE TABLE IF NOT EXISTS salt.salt_returns ( jid text, minion_id text, fun text, alter_time timestamp, full_ret text, return text, success boolean, PRIMARY KEY (jid, minion_id, fun) ) WITH CLUSTERING ORDER BY (minion_id ASC, fun ASC); CREATE INDEX IF NOT EXISTS salt_returns_minion_id ON salt.salt_returns (minion_id); CREATE INDEX IF NOT EXISTS salt_returns_fun ON salt.salt_returns (fun); CREATE TABLE IF NOT EXISTS salt.jids ( jid text PRIMARY KEY, load text ); CREATE TABLE IF NOT EXISTS salt.minions ( minion_id text PRIMARY KEY, last_fun text ); CREATE INDEX IF NOT EXISTS minions_last_fun ON salt.minions (last_fun); CREATE TABLE IF NOT EXISTS salt.salt_events ( id timeuuid, tag text, alter_time timestamp, data text, master_id text, PRIMARY KEY (id, tag) ) WITH CLUSTERING ORDER BY (tag ASC); CREATE INDEX tag ON salt.salt_events (tag); Required python modules: cassandra-driver To use the cassandra returner, append '--return cassandra_cql' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return_cql cassandra Note: if your Cassandra instance has not been tuned much you may benefit from altering some timeouts in `cassandra.yaml` like so: .. code-block:: yaml # How long the coordinator should wait for read operations to complete read_request_timeout_in_ms: 5000 # How long the coordinator should wait for seq or index scans to complete range_request_timeout_in_ms: 20000 # How long the coordinator should wait for writes to complete write_request_timeout_in_ms: 20000 # How long the coordinator should wait for counter writes to complete counter_write_request_timeout_in_ms: 10000 # How long a coordinator should continue to retry a CAS operation # that contends with other proposals for the same row cas_contention_timeout_in_ms: 5000 # How long the coordinator should wait for truncates to complete # (This can be much longer, because unless auto_snapshot is disabled # we need to flush first so we can snapshot before removing the data.) truncate_request_timeout_in_ms: 60000 # The default timeout for other, miscellaneous operations request_timeout_in_ms: 20000 As always, your mileage may vary and your Cassandra cluster may have different needs. SaltStack has seen situations where these timeouts can resolve some stacktraces that appear to come from the Datastax Python driver. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import uuid import time # Import salt libs import salt.returners import salt.utils.jid import salt.utils.json import salt.exceptions from salt.exceptions import CommandExecutionError from salt.ext import six # Import third party libs try: # The following imports are not directly required by this module. Rather, # they are required by the modules/cassandra_cql execution module, on which # this module depends. # # This returner cross-calls the cassandra_cql execution module using the __salt__ dunder. # # The modules/cassandra_cql execution module will not load if the DataStax Python Driver # for Apache Cassandra is not installed. # # This module will try to load all of the 3rd party dependencies on which the # modules/cassandra_cql execution module depends. # # Effectively, if the DataStax Python Driver for Apache Cassandra is not # installed, both the modules/cassandra_cql execution module and this returner module # will not be loaded by Salt's loader system. # pylint: disable=unused-import from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, ConnectionShutdown from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=unused-import HAS_CASSANDRA_DRIVER = True except ImportError as e: HAS_CASSANDRA_DRIVER = False log = logging.getLogger(__name__) # Define the module's virtual name # # The 'cassandra' __virtualname__ is already taken by the # returners/cassandra_return module, which utilizes nodetool. This module # cross-calls the modules/cassandra_cql execution module, which uses the # DataStax Python Driver for Apache Cassandra. Namespacing allows both the # modules/cassandra_cql and returners/cassandra_cql modules to use the # virtualname 'cassandra_cql'. __virtualname__ = 'cassandra_cql' def __virtual__(): if not HAS_CASSANDRA_DRIVER: return False, 'Could not import cassandra_cql returner; ' \ 'cassandra-driver is not installed.' return True def _get_keyspace(): ''' Return keyspace if it is specified at opts, if not, use default keyspace 'salt'. ''' return (__opts__.get('cassandra', {}) or {}).get('keyspace', 'salt') def returner(ret): ''' Return data to one of potentially many clustered cassandra nodes ''' query = '''INSERT INTO {keyspace}.salt_returns ( jid, minion_id, fun, alter_time, full_ret, return, success ) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['jid']), '{0}'.format(ret['id']), '{0}'.format(ret['fun']), int(time.time() * 1000), salt.utils.json.dumps(ret).replace("'", "''"), salt.utils.json.dumps(ret['return']).replace("'", "''"), ret.get('success', False)] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_return', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not insert into salt_returns with Cassandra returner.') raise except Exception as e: log.critical('Unexpected error while inserting into salt_returns: %s', e) raise # Store the last function called by the minion # The data in salt.minions will be used by get_fun and get_minions query = '''INSERT INTO {keyspace}.minions ( minion_id, last_fun ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'returner_minion', tuple(statement_arguments), asynchronous=True) except CommandExecutionError: log.critical('Could not store minion ID with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting minion ID into the minions ' 'table: %s', e ) raise def event_return(events): ''' Return event to one of potentially many clustered cassandra nodes Requires that configuration be enabled via 'event_return' option in master config. Cassandra does not support an auto-increment feature due to the highly inefficient nature of creating a monotonically increasing number across all nodes in a distributed database. Each event will be assigned a uuid by the connecting client. ''' for event in events: tag = event.get('tag', '') data = event.get('data', '') query = '''INSERT INTO {keyspace}.salt_events ( id, alter_time, data, master_id, tag ) VALUES ( ?, ?, ?, ?, ?) '''.format(keyspace=_get_keyspace()) statement_arguments = [six.text_type(uuid.uuid1()), int(time.time() * 1000), salt.utils.json.dumps(data).replace("'", "''"), __opts__['id'], tag] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not store events with Cassandra returner.') raise except Exception as e: log.critical( 'Unexpected error while inserting into salt_events: %s', e) raise def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' # Load is being stored as a text datatype. Single quotes are used in the # VALUES list. Therefore, all single quotes contained in the results from # salt.utils.json.dumps(load) must be escaped Cassandra style. query = '''INSERT INTO {keyspace}.jids ( jid, load ) VALUES (?, ?)'''.format(keyspace=_get_keyspace()) statement_arguments = [ jid, salt.utils.json.dumps(load).replace("'", "''") ] # cassandra_cql.cql_query may raise a CommandExecutionError try: __salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load', statement_arguments, asynchronous=True) except CommandExecutionError: log.critical('Could not save load in jids table.') raise except Exception as e: log.critical('Unexpected error while inserting into jids: %s', e) raise def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass # salt-run jobs.list_jobs FAILED def get_load(jid): ''' Return the load data that marks a specified jid ''' query = '''SELECT load FROM {keyspace}.jids WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_load', [jid]) if data: load = data[0].get('load') if load: ret = salt.utils.json.loads(load) except CommandExecutionError: log.critical('Could not get load from jids table.') raise except Exception as e: log.critical('Unexpected error while getting load from jids: %s', e) raise return ret # salt-call ret.get_jid cassandra_cql 20150327234537907315 PASSED def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns WHERE jid = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if minion and full_ret: ret[minion] = salt.utils.json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical( 'Unexpected error while getting job specific information: %s', e) raise return ret # salt-call ret.get_fun cassandra_cql test.ping PASSED def get_fun(fun): ''' Return a dict of the last function called for all minions ''' query = '''SELECT minion_id, last_fun FROM {keyspace}.minions WHERE last_fun = ?;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun]) if data: for row in data: minion = row.get('minion_id') last_fun = row.get('last_fun') if minion and last_fun: ret[minion] = last_fun except CommandExecutionError: log.critical('Could not get the list of minions.') raise except Exception as e: log.critical( 'Unexpected error while getting list of minions: %s', e) raise return ret # salt-call ret.get_jids cassandra_cql PASSED def get_jids(): ''' Return a list of all job ids ''' query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace()) ret = {} # cassandra_cql.cql_query may raise a CommandExecutionError try: data = __salt__['cassandra_cql.cql_query'](query) if data: for row in data: jid = row.get('jid') load = row.get('load') if jid and load: ret[jid] = salt.utils.jid.format_jid_instance( jid, salt.utils.json.loads(load)) except CommandExecutionError: log.critical('Could not get a list of all job ids.') raise except Exception as e: log.critical( 'Unexpected error while getting list of all job ids: %s', e) raise return ret # salt-call ret.get_minions cassandra_cql PASSED def prep_jid(nocache, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
saltstack/salt
salt/output/json_out.py
output
python
def output(data, **kwargs): # pylint: disable=unused-argument ''' Print the output data in JSON ''' try: if 'output_indent' not in __opts__: return salt.utils.json.dumps(data, default=repr, indent=4) indent = __opts__.get('output_indent') sort_keys = False if indent is None: indent = None elif indent == 'pretty': indent = 4 sort_keys = True elif isinstance(indent, int): if indent >= 0: indent = indent else: indent = None return salt.utils.json.dumps(data, default=repr, indent=indent, sort_keys=sort_keys) except UnicodeDecodeError as exc: log.error('Unable to serialize output to json') return salt.utils.json.dumps( {'error': 'Unable to serialize output to json', 'message': six.text_type(exc)} ) except TypeError: log.debug('An error occurred while outputting JSON', exc_info=True) # Return valid JSON for unserializable objects return salt.utils.json.dumps({})
Print the output data in JSON
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/json_out.py#L56-L92
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\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 orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n" ]
# -*- coding: utf-8 -*- ''' Display return data in JSON format ================================== :configuration: The output format can be configured in two ways: Using the ``--out-indent`` CLI flag and specifying a positive integer or a negative integer to group JSON from each minion to a single line. Or setting the ``output_indent`` setting in the Master or Minion configuration file with one of the following values: * ``Null``: put each minion return on a single line. * ``pretty``: use four-space indents and sort the keys. * An integer: specify the indentation level. Salt's outputters operate on a per-minion basis. Each minion return will be output as a single JSON object once it comes in to the master. Some JSON parsers can guess when an object ends and a new one begins but many can not. A good way to differentiate between each minion return is to use the single-line output format and to parse each line individually. Example output (truncated):: {"dave": {"en0": {"hwaddr": "02:b0:26:32:4c:69", ...}}} {"jerry": {"en0": {"hwaddr": "02:26:ab:0d:b9:0d", ...}}} {"kevin": {"en0": {"hwaddr": "02:6d:7f:ce:9f:ee", ...}}} {"mike": {"en0": {"hwaddr": "02:48:a2:4b:70:a0", ...}}} {"phill": {"en0": {"hwaddr": "02:1d:cc:a2:33:55", ...}}} {"stuart": {"en0": {"hwaddr": "02:9a:e0:ea:9e:3c", ...}}} ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'json' def __virtual__(): ''' Rename to json ''' return __virtualname__
saltstack/salt
salt/states/mssql_role.py
present
python
def present(name, owner=None, grants=None, **kwargs): ''' Ensure that the named database is present with the specified options name The name of the database to manage owner Adds owner using AUTHORIZATION option Grants Can only be a list of strings ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if __salt__['mssql.role_exists'](name, **kwargs): ret['comment'] = 'Role {0} is already present (Not going to try to set its grants)'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Role {0} is set to be added'.format(name) return ret role_created = __salt__['mssql.role_create'](name, owner=owner, grants=grants, **kwargs) if role_created is not True: # Non-empty strings are also evaluated to True, so we cannot use if not role_created: ret['result'] = False ret['comment'] += 'Role {0} failed to be created: {1}'.format(name, role_created) return ret ret['comment'] += 'Role {0} has been added'.format(name) ret['changes'][name] = 'Present' return ret
Ensure that the named database is present with the specified options name The name of the database to manage owner Adds owner using AUTHORIZATION option Grants Can only be a list of strings
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mssql_role.py#L24-L55
null
# -*- coding: utf-8 -*- ''' Management of Microsoft SQLServer Databases =========================================== The mssql_role module is used to create and manage SQL Server Roles .. code-block:: yaml yolo: mssql_role.present ''' from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the mssql module is present ''' return 'mssql.version' in __salt__ def absent(name, **kwargs): ''' Ensure that the named database is absent name The name of the database to remove ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not __salt__['mssql.role_exists'](name): ret['comment'] = 'Role {0} is not present'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Role {0} is set to be removed'.format(name) return ret if __salt__['mssql.role_remove'](name, **kwargs): ret['comment'] = 'Role {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret # else: ret['result'] = False ret['comment'] = 'Role {0} failed to be removed'.format(name) return ret
saltstack/salt
salt/modules/servicenow.py
set_change_request_state
python
def set_change_request_state(change_id, state='approved'): ''' Set the approval state of a change request/record :param change_id: The ID of the change request, e.g. CHG123545 :type change_id: ``str`` :param state: The target state, e.g. approved :type state: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.set_change_request_state CHG000123 declined salt myminion servicenow.set_change_request_state CHG000123 approved ''' client = _get_client() client.table = 'change_request' # Get the change record first record = client.get({'number': change_id}) if not record: log.error('Failed to fetch change record, maybe it does not exist?') return False # Use the sys_id as the unique system record sys_id = record[0]['sys_id'] response = client.update({'approval': state}, sys_id) return response
Set the approval state of a change request/record :param change_id: The ID of the change request, e.g. CHG123545 :type change_id: ``str`` :param state: The target state, e.g. approved :type state: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.set_change_request_state CHG000123 declined salt myminion servicenow.set_change_request_state CHG000123 approved
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/servicenow.py#L61-L88
[ "def _get_client():\n config = __salt__['config.option'](SERVICE_NAME)\n instance_name = config['instance_name']\n username = config['username']\n password = config['password']\n return Client(instance_name, username, password)\n" ]
# -*- coding: utf-8 -*- ''' Module for execution of ServiceNow CI (configuration items) .. versionadded:: 2016.11.0 :depends: servicenow_rest python module :configuration: Configure this module by specifying the name of a configuration profile in the minion config, minion pillar, or master config. The module will use the 'servicenow' key by default, if defined. For example: .. code-block:: yaml servicenow: instance_name: '' username: '' password: '' ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import third party libs from salt.ext import six HAS_LIBS = False try: from servicenow_rest.api import Client HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'servicenow' SERVICE_NAME = 'servicenow' def __virtual__(): ''' Only load this module if servicenow is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The servicenow execution module failed to load: ' 'requires servicenow_rest python library to be installed.') def _get_client(): config = __salt__['config.option'](SERVICE_NAME) instance_name = config['instance_name'] username = config['username'] password = config['password'] return Client(instance_name, username, password) def delete_record(table, sys_id): ''' Delete an existing record :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.delete_record sys_computer 2134566 ''' client = _get_client() client.table = table response = client.delete(sys_id) return response def non_structured_query(table, query=None, **kwargs): ''' Run a non-structed (not a dict) query on a servicenow table. See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0 for help on constructing a non-structured query string. :param table: The table name, e.g. sys_user :type table: ``str`` :param query: The query to run (or use keyword arguments to filter data) :type query: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.non_structured_query sys_computer 'role=web' salt myminion servicenow.non_structured_query sys_computer role=web type=computer ''' client = _get_client() client.table = table # underlying lib doesn't use six or past.basestring, # does isinstance(x, str) # http://bit.ly/1VkMmpE if query is None: # try and assemble a query by keyword query_parts = [] for key, value in kwargs.items(): query_parts.append('{0}={1}'.format(key, value)) query = '^'.join(query_parts) query = six.text_type(query) response = client.get(query) return response def update_record_field(table, sys_id, field, value): ''' Update the value of a record's field in a servicenow table :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` :param field: The new value :type field: ``str`` :param value: The new value :type value: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy ''' client = _get_client() client.table = table response = client.update({field: value}, sys_id) return response
saltstack/salt
salt/modules/servicenow.py
delete_record
python
def delete_record(table, sys_id): ''' Delete an existing record :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.delete_record sys_computer 2134566 ''' client = _get_client() client.table = table response = client.delete(sys_id) return response
Delete an existing record :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.delete_record sys_computer 2134566
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/servicenow.py#L91-L110
[ "def _get_client():\n config = __salt__['config.option'](SERVICE_NAME)\n instance_name = config['instance_name']\n username = config['username']\n password = config['password']\n return Client(instance_name, username, password)\n" ]
# -*- coding: utf-8 -*- ''' Module for execution of ServiceNow CI (configuration items) .. versionadded:: 2016.11.0 :depends: servicenow_rest python module :configuration: Configure this module by specifying the name of a configuration profile in the minion config, minion pillar, or master config. The module will use the 'servicenow' key by default, if defined. For example: .. code-block:: yaml servicenow: instance_name: '' username: '' password: '' ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import third party libs from salt.ext import six HAS_LIBS = False try: from servicenow_rest.api import Client HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'servicenow' SERVICE_NAME = 'servicenow' def __virtual__(): ''' Only load this module if servicenow is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The servicenow execution module failed to load: ' 'requires servicenow_rest python library to be installed.') def _get_client(): config = __salt__['config.option'](SERVICE_NAME) instance_name = config['instance_name'] username = config['username'] password = config['password'] return Client(instance_name, username, password) def set_change_request_state(change_id, state='approved'): ''' Set the approval state of a change request/record :param change_id: The ID of the change request, e.g. CHG123545 :type change_id: ``str`` :param state: The target state, e.g. approved :type state: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.set_change_request_state CHG000123 declined salt myminion servicenow.set_change_request_state CHG000123 approved ''' client = _get_client() client.table = 'change_request' # Get the change record first record = client.get({'number': change_id}) if not record: log.error('Failed to fetch change record, maybe it does not exist?') return False # Use the sys_id as the unique system record sys_id = record[0]['sys_id'] response = client.update({'approval': state}, sys_id) return response def non_structured_query(table, query=None, **kwargs): ''' Run a non-structed (not a dict) query on a servicenow table. See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0 for help on constructing a non-structured query string. :param table: The table name, e.g. sys_user :type table: ``str`` :param query: The query to run (or use keyword arguments to filter data) :type query: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.non_structured_query sys_computer 'role=web' salt myminion servicenow.non_structured_query sys_computer role=web type=computer ''' client = _get_client() client.table = table # underlying lib doesn't use six or past.basestring, # does isinstance(x, str) # http://bit.ly/1VkMmpE if query is None: # try and assemble a query by keyword query_parts = [] for key, value in kwargs.items(): query_parts.append('{0}={1}'.format(key, value)) query = '^'.join(query_parts) query = six.text_type(query) response = client.get(query) return response def update_record_field(table, sys_id, field, value): ''' Update the value of a record's field in a servicenow table :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` :param field: The new value :type field: ``str`` :param value: The new value :type value: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy ''' client = _get_client() client.table = table response = client.update({field: value}, sys_id) return response
saltstack/salt
salt/modules/servicenow.py
non_structured_query
python
def non_structured_query(table, query=None, **kwargs): ''' Run a non-structed (not a dict) query on a servicenow table. See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0 for help on constructing a non-structured query string. :param table: The table name, e.g. sys_user :type table: ``str`` :param query: The query to run (or use keyword arguments to filter data) :type query: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.non_structured_query sys_computer 'role=web' salt myminion servicenow.non_structured_query sys_computer role=web type=computer ''' client = _get_client() client.table = table # underlying lib doesn't use six or past.basestring, # does isinstance(x, str) # http://bit.ly/1VkMmpE if query is None: # try and assemble a query by keyword query_parts = [] for key, value in kwargs.items(): query_parts.append('{0}={1}'.format(key, value)) query = '^'.join(query_parts) query = six.text_type(query) response = client.get(query) return response
Run a non-structed (not a dict) query on a servicenow table. See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0 for help on constructing a non-structured query string. :param table: The table name, e.g. sys_user :type table: ``str`` :param query: The query to run (or use keyword arguments to filter data) :type query: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.non_structured_query sys_computer 'role=web' salt myminion servicenow.non_structured_query sys_computer role=web type=computer
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/servicenow.py#L113-L145
[ "def _get_client():\n config = __salt__['config.option'](SERVICE_NAME)\n instance_name = config['instance_name']\n username = config['username']\n password = config['password']\n return Client(instance_name, username, password)\n" ]
# -*- coding: utf-8 -*- ''' Module for execution of ServiceNow CI (configuration items) .. versionadded:: 2016.11.0 :depends: servicenow_rest python module :configuration: Configure this module by specifying the name of a configuration profile in the minion config, minion pillar, or master config. The module will use the 'servicenow' key by default, if defined. For example: .. code-block:: yaml servicenow: instance_name: '' username: '' password: '' ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import third party libs from salt.ext import six HAS_LIBS = False try: from servicenow_rest.api import Client HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'servicenow' SERVICE_NAME = 'servicenow' def __virtual__(): ''' Only load this module if servicenow is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The servicenow execution module failed to load: ' 'requires servicenow_rest python library to be installed.') def _get_client(): config = __salt__['config.option'](SERVICE_NAME) instance_name = config['instance_name'] username = config['username'] password = config['password'] return Client(instance_name, username, password) def set_change_request_state(change_id, state='approved'): ''' Set the approval state of a change request/record :param change_id: The ID of the change request, e.g. CHG123545 :type change_id: ``str`` :param state: The target state, e.g. approved :type state: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.set_change_request_state CHG000123 declined salt myminion servicenow.set_change_request_state CHG000123 approved ''' client = _get_client() client.table = 'change_request' # Get the change record first record = client.get({'number': change_id}) if not record: log.error('Failed to fetch change record, maybe it does not exist?') return False # Use the sys_id as the unique system record sys_id = record[0]['sys_id'] response = client.update({'approval': state}, sys_id) return response def delete_record(table, sys_id): ''' Delete an existing record :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.delete_record sys_computer 2134566 ''' client = _get_client() client.table = table response = client.delete(sys_id) return response def update_record_field(table, sys_id, field, value): ''' Update the value of a record's field in a servicenow table :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` :param field: The new value :type field: ``str`` :param value: The new value :type value: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy ''' client = _get_client() client.table = table response = client.update({field: value}, sys_id) return response
saltstack/salt
salt/modules/servicenow.py
update_record_field
python
def update_record_field(table, sys_id, field, value): ''' Update the value of a record's field in a servicenow table :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` :param field: The new value :type field: ``str`` :param value: The new value :type value: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy ''' client = _get_client() client.table = table response = client.update({field: value}, sys_id) return response
Update the value of a record's field in a servicenow table :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` :param field: The new value :type field: ``str`` :param value: The new value :type value: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/servicenow.py#L148-L173
[ "def _get_client():\n config = __salt__['config.option'](SERVICE_NAME)\n instance_name = config['instance_name']\n username = config['username']\n password = config['password']\n return Client(instance_name, username, password)\n" ]
# -*- coding: utf-8 -*- ''' Module for execution of ServiceNow CI (configuration items) .. versionadded:: 2016.11.0 :depends: servicenow_rest python module :configuration: Configure this module by specifying the name of a configuration profile in the minion config, minion pillar, or master config. The module will use the 'servicenow' key by default, if defined. For example: .. code-block:: yaml servicenow: instance_name: '' username: '' password: '' ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import third party libs from salt.ext import six HAS_LIBS = False try: from servicenow_rest.api import Client HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'servicenow' SERVICE_NAME = 'servicenow' def __virtual__(): ''' Only load this module if servicenow is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The servicenow execution module failed to load: ' 'requires servicenow_rest python library to be installed.') def _get_client(): config = __salt__['config.option'](SERVICE_NAME) instance_name = config['instance_name'] username = config['username'] password = config['password'] return Client(instance_name, username, password) def set_change_request_state(change_id, state='approved'): ''' Set the approval state of a change request/record :param change_id: The ID of the change request, e.g. CHG123545 :type change_id: ``str`` :param state: The target state, e.g. approved :type state: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.set_change_request_state CHG000123 declined salt myminion servicenow.set_change_request_state CHG000123 approved ''' client = _get_client() client.table = 'change_request' # Get the change record first record = client.get({'number': change_id}) if not record: log.error('Failed to fetch change record, maybe it does not exist?') return False # Use the sys_id as the unique system record sys_id = record[0]['sys_id'] response = client.update({'approval': state}, sys_id) return response def delete_record(table, sys_id): ''' Delete an existing record :param table: The table name, e.g. sys_user :type table: ``str`` :param sys_id: The unique ID of the record :type sys_id: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.delete_record sys_computer 2134566 ''' client = _get_client() client.table = table response = client.delete(sys_id) return response def non_structured_query(table, query=None, **kwargs): ''' Run a non-structed (not a dict) query on a servicenow table. See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0 for help on constructing a non-structured query string. :param table: The table name, e.g. sys_user :type table: ``str`` :param query: The query to run (or use keyword arguments to filter data) :type query: ``str`` CLI Example: .. code-block:: bash salt myminion servicenow.non_structured_query sys_computer 'role=web' salt myminion servicenow.non_structured_query sys_computer role=web type=computer ''' client = _get_client() client.table = table # underlying lib doesn't use six or past.basestring, # does isinstance(x, str) # http://bit.ly/1VkMmpE if query is None: # try and assemble a query by keyword query_parts = [] for key, value in kwargs.items(): query_parts.append('{0}={1}'.format(key, value)) query = '^'.join(query_parts) query = six.text_type(query) response = client.get(query) return response
saltstack/salt
salt/states/cabal.py
_parse_pkg_string
python
def _parse_pkg_string(pkg): ''' Parse pkg string and return a tuple of package name, separator, and package version. Cabal support install package with following format: * foo-1.0 * foo < 1.2 * foo > 1.3 For the sake of simplicity only the first form is supported, support for other forms can be added later. ''' pkg_name, separator, pkg_ver = pkg.partition('-') return (pkg_name.strip(), separator, pkg_ver.strip())
Parse pkg string and return a tuple of package name, separator, and package version. Cabal support install package with following format: * foo-1.0 * foo < 1.2 * foo > 1.3 For the sake of simplicity only the first form is supported, support for other forms can be added later.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cabal.py#L40-L55
null
# -*- coding: utf-8 -*- ''' Installation of Cabal Packages ============================== .. versionadded:: 2015.8.0 These states manage the installed packages for Haskell using cabal. Note that cabal-install must be installed for these states to be available, so cabal states should include a requisite to a pkg.installed state for the package which provides cabal (``cabal-install`` in case of Debian based distributions). Example:: .. code-block:: yaml cabal-install: pkg.installed ShellCheck: cabal.installed: - require: - pkg: cabal-install ''' from __future__ import absolute_import, print_function, unicode_literals from salt.exceptions import CommandExecutionError, CommandNotFoundError import salt.utils.path def __virtual__(): ''' Only work when cabal-install is installed. ''' return (salt.utils.path.which('cabal') is not None) and \ (salt.utils.path.which('ghc-pkg') is not None) def installed(name, pkgs=None, user=None, install_global=False, env=None): ''' Verify that the given package is installed and is at the correct version (if specified). .. code-block:: yaml ShellCheck-0.3.5: cabal: - installed: name The package to install user The user to run cabal install with install_global Install package globally instead of locally env A list of environment variables to be set prior to execution. The format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`. state function. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} try: call = __salt__['cabal.update'](user=user, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Could not run cabal update {0}'.format(err) return ret if pkgs is not None: pkg_list = pkgs else: pkg_list = [name] try: installed_pkgs = __salt__['cabal.list']( user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err) return ret pkgs_satisfied = [] pkgs_to_install = [] for pkg in pkg_list: pkg_name, _, pkg_ver = _parse_pkg_string(pkg) if pkg_name not in installed_pkgs: pkgs_to_install.append(pkg) else: if pkg_ver: # version is specified if installed_pkgs[pkg_name] != pkg_ver: pkgs_to_install.append(pkg) else: pkgs_satisfied.append(pkg) else: pkgs_satisfied.append(pkg) if __opts__['test']: ret['result'] = None comment_msg = [] if pkgs_to_install: comment_msg.append( 'Packages(s) \'{0}\' are set to be installed'.format( ', '.join(pkgs_to_install))) if pkgs_satisfied: comment_msg.append( 'Packages(s) \'{0}\' satisfied by {1}'.format( ', '.join(pkg_list), ', '.join(pkgs_satisfied))) ret['comment'] = '. '.join(comment_msg) return ret if not pkgs_to_install: ret['result'] = True ret['comment'] = ('Packages(s) \'{0}\' satisfied by {1}'.format( ', '.join(pkg_list), ', '.join(pkgs_satisfied))) return ret try: call = __salt__['cabal.install'](pkgs=pkg_list, user=user, install_global=install_global, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error installing \'{0}\': {1}'.format( ', '.join(pkg_list), err) return ret if call and isinstance(call, dict): ret['result'] = True ret['changes'] = {'old': [], 'new': pkgs_to_install} ret['comment'] = 'Packages(s) \'{0}\' successfully installed'.format( ', '.join(pkgs_to_install)) else: ret['result'] = False ret['comment'] = 'Could not install packages(s) \'{0}\''.format( ', '.join(pkg_list)) return ret def removed(name, user=None, env=None): ''' Verify that given package is not installed. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} try: installed_pkgs = __salt__['cabal.list']( user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err) if name not in installed_pkgs: ret['result'] = True ret['comment'] = 'Package \'{0}\' is not installed'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Package \'{0}\' is set to be removed'.format(name) return ret if __salt__['cabal.uninstall'](pkg=name, user=user, env=env): ret['result'] = True ret['changes'][name] = 'Removed' ret['comment'] = 'Package \'{0}\' was successfully removed'.format(name) else: ret['result'] = False ret['comment'] = 'Error removing package \'{0}\''.format(name) return ret
saltstack/salt
salt/states/cabal.py
installed
python
def installed(name, pkgs=None, user=None, install_global=False, env=None): ''' Verify that the given package is installed and is at the correct version (if specified). .. code-block:: yaml ShellCheck-0.3.5: cabal: - installed: name The package to install user The user to run cabal install with install_global Install package globally instead of locally env A list of environment variables to be set prior to execution. The format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`. state function. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} try: call = __salt__['cabal.update'](user=user, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Could not run cabal update {0}'.format(err) return ret if pkgs is not None: pkg_list = pkgs else: pkg_list = [name] try: installed_pkgs = __salt__['cabal.list']( user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err) return ret pkgs_satisfied = [] pkgs_to_install = [] for pkg in pkg_list: pkg_name, _, pkg_ver = _parse_pkg_string(pkg) if pkg_name not in installed_pkgs: pkgs_to_install.append(pkg) else: if pkg_ver: # version is specified if installed_pkgs[pkg_name] != pkg_ver: pkgs_to_install.append(pkg) else: pkgs_satisfied.append(pkg) else: pkgs_satisfied.append(pkg) if __opts__['test']: ret['result'] = None comment_msg = [] if pkgs_to_install: comment_msg.append( 'Packages(s) \'{0}\' are set to be installed'.format( ', '.join(pkgs_to_install))) if pkgs_satisfied: comment_msg.append( 'Packages(s) \'{0}\' satisfied by {1}'.format( ', '.join(pkg_list), ', '.join(pkgs_satisfied))) ret['comment'] = '. '.join(comment_msg) return ret if not pkgs_to_install: ret['result'] = True ret['comment'] = ('Packages(s) \'{0}\' satisfied by {1}'.format( ', '.join(pkg_list), ', '.join(pkgs_satisfied))) return ret try: call = __salt__['cabal.install'](pkgs=pkg_list, user=user, install_global=install_global, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error installing \'{0}\': {1}'.format( ', '.join(pkg_list), err) return ret if call and isinstance(call, dict): ret['result'] = True ret['changes'] = {'old': [], 'new': pkgs_to_install} ret['comment'] = 'Packages(s) \'{0}\' successfully installed'.format( ', '.join(pkgs_to_install)) else: ret['result'] = False ret['comment'] = 'Could not install packages(s) \'{0}\''.format( ', '.join(pkg_list)) return ret
Verify that the given package is installed and is at the correct version (if specified). .. code-block:: yaml ShellCheck-0.3.5: cabal: - installed: name The package to install user The user to run cabal install with install_global Install package globally instead of locally env A list of environment variables to be set prior to execution. The format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`. state function.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cabal.py#L58-L169
[ "def _parse_pkg_string(pkg):\n '''\n Parse pkg string and return a tuple of package name, separator, and\n package version.\n\n Cabal support install package with following format:\n\n * foo-1.0\n * foo < 1.2\n * foo > 1.3\n\n For the sake of simplicity only the first form is supported,\n support for other forms can be added later.\n '''\n pkg_name, separator, pkg_ver = pkg.partition('-')\n return (pkg_name.strip(), separator, pkg_ver.strip())\n" ]
# -*- coding: utf-8 -*- ''' Installation of Cabal Packages ============================== .. versionadded:: 2015.8.0 These states manage the installed packages for Haskell using cabal. Note that cabal-install must be installed for these states to be available, so cabal states should include a requisite to a pkg.installed state for the package which provides cabal (``cabal-install`` in case of Debian based distributions). Example:: .. code-block:: yaml cabal-install: pkg.installed ShellCheck: cabal.installed: - require: - pkg: cabal-install ''' from __future__ import absolute_import, print_function, unicode_literals from salt.exceptions import CommandExecutionError, CommandNotFoundError import salt.utils.path def __virtual__(): ''' Only work when cabal-install is installed. ''' return (salt.utils.path.which('cabal') is not None) and \ (salt.utils.path.which('ghc-pkg') is not None) def _parse_pkg_string(pkg): ''' Parse pkg string and return a tuple of package name, separator, and package version. Cabal support install package with following format: * foo-1.0 * foo < 1.2 * foo > 1.3 For the sake of simplicity only the first form is supported, support for other forms can be added later. ''' pkg_name, separator, pkg_ver = pkg.partition('-') return (pkg_name.strip(), separator, pkg_ver.strip()) def removed(name, user=None, env=None): ''' Verify that given package is not installed. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} try: installed_pkgs = __salt__['cabal.list']( user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err) if name not in installed_pkgs: ret['result'] = True ret['comment'] = 'Package \'{0}\' is not installed'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Package \'{0}\' is set to be removed'.format(name) return ret if __salt__['cabal.uninstall'](pkg=name, user=user, env=env): ret['result'] = True ret['changes'][name] = 'Removed' ret['comment'] = 'Package \'{0}\' was successfully removed'.format(name) else: ret['result'] = False ret['comment'] = 'Error removing package \'{0}\''.format(name) return ret
saltstack/salt
salt/states/cabal.py
removed
python
def removed(name, user=None, env=None): ''' Verify that given package is not installed. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} try: installed_pkgs = __salt__['cabal.list']( user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err) if name not in installed_pkgs: ret['result'] = True ret['comment'] = 'Package \'{0}\' is not installed'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Package \'{0}\' is set to be removed'.format(name) return ret if __salt__['cabal.uninstall'](pkg=name, user=user, env=env): ret['result'] = True ret['changes'][name] = 'Removed' ret['comment'] = 'Package \'{0}\' was successfully removed'.format(name) else: ret['result'] = False ret['comment'] = 'Error removing package \'{0}\''.format(name) return ret
Verify that given package is not installed.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cabal.py#L172-L206
null
# -*- coding: utf-8 -*- ''' Installation of Cabal Packages ============================== .. versionadded:: 2015.8.0 These states manage the installed packages for Haskell using cabal. Note that cabal-install must be installed for these states to be available, so cabal states should include a requisite to a pkg.installed state for the package which provides cabal (``cabal-install`` in case of Debian based distributions). Example:: .. code-block:: yaml cabal-install: pkg.installed ShellCheck: cabal.installed: - require: - pkg: cabal-install ''' from __future__ import absolute_import, print_function, unicode_literals from salt.exceptions import CommandExecutionError, CommandNotFoundError import salt.utils.path def __virtual__(): ''' Only work when cabal-install is installed. ''' return (salt.utils.path.which('cabal') is not None) and \ (salt.utils.path.which('ghc-pkg') is not None) def _parse_pkg_string(pkg): ''' Parse pkg string and return a tuple of package name, separator, and package version. Cabal support install package with following format: * foo-1.0 * foo < 1.2 * foo > 1.3 For the sake of simplicity only the first form is supported, support for other forms can be added later. ''' pkg_name, separator, pkg_ver = pkg.partition('-') return (pkg_name.strip(), separator, pkg_ver.strip()) def installed(name, pkgs=None, user=None, install_global=False, env=None): ''' Verify that the given package is installed and is at the correct version (if specified). .. code-block:: yaml ShellCheck-0.3.5: cabal: - installed: name The package to install user The user to run cabal install with install_global Install package globally instead of locally env A list of environment variables to be set prior to execution. The format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`. state function. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} try: call = __salt__['cabal.update'](user=user, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Could not run cabal update {0}'.format(err) return ret if pkgs is not None: pkg_list = pkgs else: pkg_list = [name] try: installed_pkgs = __salt__['cabal.list']( user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err) return ret pkgs_satisfied = [] pkgs_to_install = [] for pkg in pkg_list: pkg_name, _, pkg_ver = _parse_pkg_string(pkg) if pkg_name not in installed_pkgs: pkgs_to_install.append(pkg) else: if pkg_ver: # version is specified if installed_pkgs[pkg_name] != pkg_ver: pkgs_to_install.append(pkg) else: pkgs_satisfied.append(pkg) else: pkgs_satisfied.append(pkg) if __opts__['test']: ret['result'] = None comment_msg = [] if pkgs_to_install: comment_msg.append( 'Packages(s) \'{0}\' are set to be installed'.format( ', '.join(pkgs_to_install))) if pkgs_satisfied: comment_msg.append( 'Packages(s) \'{0}\' satisfied by {1}'.format( ', '.join(pkg_list), ', '.join(pkgs_satisfied))) ret['comment'] = '. '.join(comment_msg) return ret if not pkgs_to_install: ret['result'] = True ret['comment'] = ('Packages(s) \'{0}\' satisfied by {1}'.format( ', '.join(pkg_list), ', '.join(pkgs_satisfied))) return ret try: call = __salt__['cabal.install'](pkgs=pkg_list, user=user, install_global=install_global, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret['result'] = False ret['comment'] = 'Error installing \'{0}\': {1}'.format( ', '.join(pkg_list), err) return ret if call and isinstance(call, dict): ret['result'] = True ret['changes'] = {'old': [], 'new': pkgs_to_install} ret['comment'] = 'Packages(s) \'{0}\' successfully installed'.format( ', '.join(pkgs_to_install)) else: ret['result'] = False ret['comment'] = 'Could not install packages(s) \'{0}\''.format( ', '.join(pkg_list)) return ret
saltstack/salt
salt/beacons/service.py
beacon
python
def beacon(config): ''' Scan for the configured services and fire events Example Config .. code-block:: yaml beacons: service: - services: salt-master: {} mysql: {} The config above sets up beacons to check for the salt-master and mysql services. The config also supports two other parameters for each service: `onchangeonly`: when `onchangeonly` is True the beacon will fire events only when the service status changes. Otherwise, it will fire an event at each beacon interval. The default is False. `delay`: when `delay` is greater than 0 the beacon will fire events only after the service status changes, and the delay (in seconds) has passed. Applicable only when `onchangeonly` is True. The default is 0. `emitatstartup`: when `emitatstartup` is False the beacon will not fire event when the minion is reload. Applicable only when `onchangeonly` is True. The default is True. `uncleanshutdown`: If `uncleanshutdown` is present it should point to the location of a pid file for the service. Most services will not clean up this pid file if they are shutdown uncleanly (e.g. via `kill -9`) or if they are terminated through a crash such as a segmentation fault. If the file is present, then the beacon will add `uncleanshutdown: True` to the event. If not present, the field will be False. The field is only added when the service is NOT running. Omitting the configuration variable altogether will turn this feature off. Please note that some init systems can remove the pid file if the service registers as crashed. One such example is nginx on CentOS 7, where the service unit removes the pid file when the service shuts down (IE: the pid file is observed as removed when kill -9 is sent to the nginx master process). The 'uncleanshutdown' option might not be of much use there, unless the unit file is modified. Here is an example that will fire an event 30 seconds after the state of nginx changes and report an uncleanshutdown. This example is for Arch, which places nginx's pid file in `/run`. .. code-block:: yaml beacons: service: - services: nginx: onchangeonly: True delay: 30 uncleanshutdown: /run/nginx.pid ''' ret = [] _config = {} list(map(_config.update, config)) for service in _config.get('services', {}): ret_dict = {} service_config = _config['services'][service] ret_dict[service] = {'running': __salt__['service.status'](service)} ret_dict['service_name'] = service ret_dict['tag'] = service currtime = time.time() # If no options is given to the service, we fall back to the defaults # assign a False value to oncleanshutdown and onchangeonly. Those # key:values are then added to the service dictionary. if not service_config: service_config = {} if 'oncleanshutdown' not in service_config: service_config['oncleanshutdown'] = False if 'emitatstartup' not in service_config: service_config['emitatstartup'] = True if 'onchangeonly' not in service_config: service_config['onchangeonly'] = False if 'delay' not in service_config: service_config['delay'] = 0 # We only want to report the nature of the shutdown # if the current running status is False # as well as if the config for the beacon asks for it if 'uncleanshutdown' in service_config and not ret_dict[service]['running']: filename = service_config['uncleanshutdown'] ret_dict[service]['uncleanshutdown'] = True if os.path.exists(filename) else False if 'onchangeonly' in service_config and service_config['onchangeonly'] is True: if service not in LAST_STATUS: LAST_STATUS[service] = ret_dict[service] if service_config['delay'] > 0: LAST_STATUS[service]['time'] = currtime elif not service_config['emitatstartup']: continue else: ret.append(ret_dict) if LAST_STATUS[service]['running'] != ret_dict[service]['running']: LAST_STATUS[service] = ret_dict[service] if service_config['delay'] > 0: LAST_STATUS[service]['time'] = currtime else: ret.append(ret_dict) if 'time' in LAST_STATUS[service]: elapsedtime = int(round(currtime - LAST_STATUS[service]['time'])) if elapsedtime > service_config['delay']: del LAST_STATUS[service]['time'] ret.append(ret_dict) else: ret.append(ret_dict) return ret
Scan for the configured services and fire events Example Config .. code-block:: yaml beacons: service: - services: salt-master: {} mysql: {} The config above sets up beacons to check for the salt-master and mysql services. The config also supports two other parameters for each service: `onchangeonly`: when `onchangeonly` is True the beacon will fire events only when the service status changes. Otherwise, it will fire an event at each beacon interval. The default is False. `delay`: when `delay` is greater than 0 the beacon will fire events only after the service status changes, and the delay (in seconds) has passed. Applicable only when `onchangeonly` is True. The default is 0. `emitatstartup`: when `emitatstartup` is False the beacon will not fire event when the minion is reload. Applicable only when `onchangeonly` is True. The default is True. `uncleanshutdown`: If `uncleanshutdown` is present it should point to the location of a pid file for the service. Most services will not clean up this pid file if they are shutdown uncleanly (e.g. via `kill -9`) or if they are terminated through a crash such as a segmentation fault. If the file is present, then the beacon will add `uncleanshutdown: True` to the event. If not present, the field will be False. The field is only added when the service is NOT running. Omitting the configuration variable altogether will turn this feature off. Please note that some init systems can remove the pid file if the service registers as crashed. One such example is nginx on CentOS 7, where the service unit removes the pid file when the service shuts down (IE: the pid file is observed as removed when kill -9 is sent to the nginx master process). The 'uncleanshutdown' option might not be of much use there, unless the unit file is modified. Here is an example that will fire an event 30 seconds after the state of nginx changes and report an uncleanshutdown. This example is for Arch, which places nginx's pid file in `/run`. .. code-block:: yaml beacons: service: - services: nginx: onchangeonly: True delay: 30 uncleanshutdown: /run/nginx.pid
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/service.py#L44-L164
null
# -*- coding: utf-8 -*- ''' Send events covering service status ''' # Import Python Libs from __future__ import absolute_import, unicode_literals import os import logging import time from salt.ext.six.moves import map log = logging.getLogger(__name__) # pylint: disable=invalid-name LAST_STATUS = {} __virtualname__ = 'service' def validate(config): ''' Validate the beacon configuration ''' # Configuration for service beacon should be a list of dicts if not isinstance(config, list): return False, ('Configuration for service beacon must be a list.') else: _config = {} list(map(_config.update, config)) if 'services' not in _config: return False, ('Configuration for service beacon' ' requires services.') else: for config_item in _config['services']: if not isinstance(_config['services'][config_item], dict): return False, ('Configuration for service beacon must ' 'be a list of dictionaries.') return True, 'Valid beacon configuration'
saltstack/salt
salt/modules/jira_mod.py
_get_credentials
python
def _get_credentials(server=None, username=None, password=None): ''' Returns the credentials merged with the config data (opts + pillar). ''' jira_cfg = __salt__['config.merge']('jira', default={}) if not server: server = jira_cfg.get('server') if not username: username = jira_cfg.get('username') if not password: password = jira_cfg.get('password') return server, username, password
Returns the credentials merged with the config data (opts + pillar).
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L50-L63
null
# -*- coding: utf-8 -*- ''' JIRA Execution module ===================== .. versionadded:: 2019.2.0 Execution module to manipulate JIRA tickets via Salt. This module requires the ``jira`` Python library to be installed. Configuration example: .. code-block:: yaml jira: server: https://jira.atlassian.org username: salt password: pass ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging log = logging.getLogger(__name__) # Import salt modules try: from salt.utils import clean_kwargs except ImportError: from salt.utils.args import clean_kwargs # Import third party modules try: import jira HAS_JIRA = True except ImportError: HAS_JIRA = False __virtualname__ = 'jira' __proxyenabled__ = ['*'] JIRA = None def __virtual__(): return __virtualname__ if HAS_JIRA else (False, 'Please install the jira Python libary from PyPI') def _get_jira(server=None, username=None, password=None): global JIRA if not JIRA: server, username, password = _get_credentials(server=server, username=username, password=password) JIRA = jira.JIRA(basic_auth=(username, password), server=server, logging=True) # We want logging return JIRA def create_issue(project, summary, description, template_engine='jinja', context=None, defaults=None, saltenv='base', issuetype='Bug', priority='Normal', labels=None, assignee=None, server=None, username=None, password=None, **kwargs): ''' Create a JIRA issue using the named settings. Return the JIRA ticket ID. project The name of the project to attach the JIRA ticket to. summary The summary (title) of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before creating the ticket. description The full body description of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before creating the ticket. template_engine: ``jinja`` The name of the template engine to be used to render the values of the ``summary`` and ``description`` arguments. Default: ``jinja``. context: ``None`` The context to pass when rendering the ``summary`` and ``description``. This argument is ignored when ``template_engine`` is set as ``None`` defaults: ``None`` Default values to pass to the Salt rendering pipeline for the ``summary`` and ``description`` arguments. This argument is ignored when ``template_engine`` is set as ``None``. saltenv: ``base`` The Salt environment name (for the rendering system). issuetype: ``Bug`` The type of the JIRA ticket. Default: ``Bug``. priority: ``Normal`` The priority of the JIRA ticket. Default: ``Normal``. labels: ``None`` A list of labels to add to the ticket. assignee: ``None`` The name of the person to assign the ticket to. CLI Examples: .. code-block:: bash salt '*' jira.create_issue NET 'Ticket title' 'Ticket description' salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja ''' if template_engine: summary = __salt__['file.apply_template_on_contents'](summary, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) description = __salt__['file.apply_template_on_contents'](description, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) jira_ = _get_jira(server=server, username=username, password=password) if not labels: labels = [] data = { 'project': { 'key': project }, 'summary': summary, 'description': description, 'issuetype': { 'name': issuetype }, 'priority': { 'name': priority }, 'labels': labels } data.update(clean_kwargs(**kwargs)) issue = jira_.create_issue(data) issue_key = str(issue) if assignee: assign_issue(issue_key, assignee) return issue_key def assign_issue(issue_key, assignee, server=None, username=None, password=None): ''' Assign the issue to an existing user. Return ``True`` when the issue has been properly assigned. issue_key The JIRA ID of the ticket to manipulate. assignee The name of the user to assign the ticket to. CLI Example: salt '*' jira.assign_issue NET-123 example_user ''' jira_ = _get_jira(server=server, username=username, password=password) assigned = jira_.assign_issue(issue_key, assignee) return assigned def add_comment(issue_key, comment, visibility=None, is_internal=False, server=None, username=None, password=None): ''' Add a comment to an existing ticket. Return ``True`` when it successfully added the comment. issue_key The issue ID to add the comment to. comment The body of the comment to be added. visibility: ``None`` A dictionary having two keys: - ``type``: is ``role`` (or ``group`` if the JIRA server has configured comment visibility for groups). - ``value``: the name of the role (or group) to which viewing of this comment will be restricted. is_internal: ``False`` Whether a comment has to be marked as ``Internal`` in Jira Service Desk. CLI Example: .. code-block:: bash salt '*' jira.add_comment NE-123 'This is a comment' ''' jira_ = _get_jira(server=server, username=username, password=password) comm = jira_.add_comment(issue_key, comment, visibility=visibility, is_internal=is_internal) return True def issue_closed(issue_key, server=None, username=None, password=None): ''' Check if the issue is closed. issue_key The JIRA iD of the ticket to close. Returns: - ``True``: the ticket exists and it is closed. - ``False``: the ticket exists and it has not been closed. - ``None``: the ticket does not exist. CLI Example: .. code-block:: bash salt '*' jira.issue_closed NE-123 ''' if not issue_key: return None jira_ = _get_jira(server=server, username=username, password=password) try: ticket = jira_.issue(issue_key) except jira.exceptions.JIRAError: # Ticket not found return None return ticket.fields().status.name == 'Closed'
saltstack/salt
salt/modules/jira_mod.py
create_issue
python
def create_issue(project, summary, description, template_engine='jinja', context=None, defaults=None, saltenv='base', issuetype='Bug', priority='Normal', labels=None, assignee=None, server=None, username=None, password=None, **kwargs): ''' Create a JIRA issue using the named settings. Return the JIRA ticket ID. project The name of the project to attach the JIRA ticket to. summary The summary (title) of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before creating the ticket. description The full body description of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before creating the ticket. template_engine: ``jinja`` The name of the template engine to be used to render the values of the ``summary`` and ``description`` arguments. Default: ``jinja``. context: ``None`` The context to pass when rendering the ``summary`` and ``description``. This argument is ignored when ``template_engine`` is set as ``None`` defaults: ``None`` Default values to pass to the Salt rendering pipeline for the ``summary`` and ``description`` arguments. This argument is ignored when ``template_engine`` is set as ``None``. saltenv: ``base`` The Salt environment name (for the rendering system). issuetype: ``Bug`` The type of the JIRA ticket. Default: ``Bug``. priority: ``Normal`` The priority of the JIRA ticket. Default: ``Normal``. labels: ``None`` A list of labels to add to the ticket. assignee: ``None`` The name of the person to assign the ticket to. CLI Examples: .. code-block:: bash salt '*' jira.create_issue NET 'Ticket title' 'Ticket description' salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja ''' if template_engine: summary = __salt__['file.apply_template_on_contents'](summary, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) description = __salt__['file.apply_template_on_contents'](description, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) jira_ = _get_jira(server=server, username=username, password=password) if not labels: labels = [] data = { 'project': { 'key': project }, 'summary': summary, 'description': description, 'issuetype': { 'name': issuetype }, 'priority': { 'name': priority }, 'labels': labels } data.update(clean_kwargs(**kwargs)) issue = jira_.create_issue(data) issue_key = str(issue) if assignee: assign_issue(issue_key, assignee) return issue_key
Create a JIRA issue using the named settings. Return the JIRA ticket ID. project The name of the project to attach the JIRA ticket to. summary The summary (title) of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before creating the ticket. description The full body description of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before creating the ticket. template_engine: ``jinja`` The name of the template engine to be used to render the values of the ``summary`` and ``description`` arguments. Default: ``jinja``. context: ``None`` The context to pass when rendering the ``summary`` and ``description``. This argument is ignored when ``template_engine`` is set as ``None`` defaults: ``None`` Default values to pass to the Salt rendering pipeline for the ``summary`` and ``description`` arguments. This argument is ignored when ``template_engine`` is set as ``None``. saltenv: ``base`` The Salt environment name (for the rendering system). issuetype: ``Bug`` The type of the JIRA ticket. Default: ``Bug``. priority: ``Normal`` The priority of the JIRA ticket. Default: ``Normal``. labels: ``None`` A list of labels to add to the ticket. assignee: ``None`` The name of the person to assign the ticket to. CLI Examples: .. code-block:: bash salt '*' jira.create_issue NET 'Ticket title' 'Ticket description' salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L80-L183
[ "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_jira(server=None,\n username=None,\n password=None):\n global JIRA\n if not JIRA:\n server, username, password = _get_credentials(server=server,\n username=username,\n password=password)\n JIRA = jira.JIRA(basic_auth=(username, password),\n server=server,\n logging=True) # We want logging\n return JIRA\n", "def assign_issue(issue_key,\n assignee,\n server=None,\n username=None,\n password=None):\n '''\n Assign the issue to an existing user. Return ``True`` when the issue has\n been properly assigned.\n\n issue_key\n The JIRA ID of the ticket to manipulate.\n\n assignee\n The name of the user to assign the ticket to.\n\n CLI Example:\n\n salt '*' jira.assign_issue NET-123 example_user\n '''\n jira_ = _get_jira(server=server,\n username=username,\n password=password)\n assigned = jira_.assign_issue(issue_key, assignee)\n return assigned\n" ]
# -*- coding: utf-8 -*- ''' JIRA Execution module ===================== .. versionadded:: 2019.2.0 Execution module to manipulate JIRA tickets via Salt. This module requires the ``jira`` Python library to be installed. Configuration example: .. code-block:: yaml jira: server: https://jira.atlassian.org username: salt password: pass ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging log = logging.getLogger(__name__) # Import salt modules try: from salt.utils import clean_kwargs except ImportError: from salt.utils.args import clean_kwargs # Import third party modules try: import jira HAS_JIRA = True except ImportError: HAS_JIRA = False __virtualname__ = 'jira' __proxyenabled__ = ['*'] JIRA = None def __virtual__(): return __virtualname__ if HAS_JIRA else (False, 'Please install the jira Python libary from PyPI') def _get_credentials(server=None, username=None, password=None): ''' Returns the credentials merged with the config data (opts + pillar). ''' jira_cfg = __salt__['config.merge']('jira', default={}) if not server: server = jira_cfg.get('server') if not username: username = jira_cfg.get('username') if not password: password = jira_cfg.get('password') return server, username, password def _get_jira(server=None, username=None, password=None): global JIRA if not JIRA: server, username, password = _get_credentials(server=server, username=username, password=password) JIRA = jira.JIRA(basic_auth=(username, password), server=server, logging=True) # We want logging return JIRA def assign_issue(issue_key, assignee, server=None, username=None, password=None): ''' Assign the issue to an existing user. Return ``True`` when the issue has been properly assigned. issue_key The JIRA ID of the ticket to manipulate. assignee The name of the user to assign the ticket to. CLI Example: salt '*' jira.assign_issue NET-123 example_user ''' jira_ = _get_jira(server=server, username=username, password=password) assigned = jira_.assign_issue(issue_key, assignee) return assigned def add_comment(issue_key, comment, visibility=None, is_internal=False, server=None, username=None, password=None): ''' Add a comment to an existing ticket. Return ``True`` when it successfully added the comment. issue_key The issue ID to add the comment to. comment The body of the comment to be added. visibility: ``None`` A dictionary having two keys: - ``type``: is ``role`` (or ``group`` if the JIRA server has configured comment visibility for groups). - ``value``: the name of the role (or group) to which viewing of this comment will be restricted. is_internal: ``False`` Whether a comment has to be marked as ``Internal`` in Jira Service Desk. CLI Example: .. code-block:: bash salt '*' jira.add_comment NE-123 'This is a comment' ''' jira_ = _get_jira(server=server, username=username, password=password) comm = jira_.add_comment(issue_key, comment, visibility=visibility, is_internal=is_internal) return True def issue_closed(issue_key, server=None, username=None, password=None): ''' Check if the issue is closed. issue_key The JIRA iD of the ticket to close. Returns: - ``True``: the ticket exists and it is closed. - ``False``: the ticket exists and it has not been closed. - ``None``: the ticket does not exist. CLI Example: .. code-block:: bash salt '*' jira.issue_closed NE-123 ''' if not issue_key: return None jira_ = _get_jira(server=server, username=username, password=password) try: ticket = jira_.issue(issue_key) except jira.exceptions.JIRAError: # Ticket not found return None return ticket.fields().status.name == 'Closed'
saltstack/salt
salt/modules/jira_mod.py
assign_issue
python
def assign_issue(issue_key, assignee, server=None, username=None, password=None): ''' Assign the issue to an existing user. Return ``True`` when the issue has been properly assigned. issue_key The JIRA ID of the ticket to manipulate. assignee The name of the user to assign the ticket to. CLI Example: salt '*' jira.assign_issue NET-123 example_user ''' jira_ = _get_jira(server=server, username=username, password=password) assigned = jira_.assign_issue(issue_key, assignee) return assigned
Assign the issue to an existing user. Return ``True`` when the issue has been properly assigned. issue_key The JIRA ID of the ticket to manipulate. assignee The name of the user to assign the ticket to. CLI Example: salt '*' jira.assign_issue NET-123 example_user
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L186-L209
[ "def _get_jira(server=None,\n username=None,\n password=None):\n global JIRA\n if not JIRA:\n server, username, password = _get_credentials(server=server,\n username=username,\n password=password)\n JIRA = jira.JIRA(basic_auth=(username, password),\n server=server,\n logging=True) # We want logging\n return JIRA\n" ]
# -*- coding: utf-8 -*- ''' JIRA Execution module ===================== .. versionadded:: 2019.2.0 Execution module to manipulate JIRA tickets via Salt. This module requires the ``jira`` Python library to be installed. Configuration example: .. code-block:: yaml jira: server: https://jira.atlassian.org username: salt password: pass ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging log = logging.getLogger(__name__) # Import salt modules try: from salt.utils import clean_kwargs except ImportError: from salt.utils.args import clean_kwargs # Import third party modules try: import jira HAS_JIRA = True except ImportError: HAS_JIRA = False __virtualname__ = 'jira' __proxyenabled__ = ['*'] JIRA = None def __virtual__(): return __virtualname__ if HAS_JIRA else (False, 'Please install the jira Python libary from PyPI') def _get_credentials(server=None, username=None, password=None): ''' Returns the credentials merged with the config data (opts + pillar). ''' jira_cfg = __salt__['config.merge']('jira', default={}) if not server: server = jira_cfg.get('server') if not username: username = jira_cfg.get('username') if not password: password = jira_cfg.get('password') return server, username, password def _get_jira(server=None, username=None, password=None): global JIRA if not JIRA: server, username, password = _get_credentials(server=server, username=username, password=password) JIRA = jira.JIRA(basic_auth=(username, password), server=server, logging=True) # We want logging return JIRA def create_issue(project, summary, description, template_engine='jinja', context=None, defaults=None, saltenv='base', issuetype='Bug', priority='Normal', labels=None, assignee=None, server=None, username=None, password=None, **kwargs): ''' Create a JIRA issue using the named settings. Return the JIRA ticket ID. project The name of the project to attach the JIRA ticket to. summary The summary (title) of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before creating the ticket. description The full body description of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before creating the ticket. template_engine: ``jinja`` The name of the template engine to be used to render the values of the ``summary`` and ``description`` arguments. Default: ``jinja``. context: ``None`` The context to pass when rendering the ``summary`` and ``description``. This argument is ignored when ``template_engine`` is set as ``None`` defaults: ``None`` Default values to pass to the Salt rendering pipeline for the ``summary`` and ``description`` arguments. This argument is ignored when ``template_engine`` is set as ``None``. saltenv: ``base`` The Salt environment name (for the rendering system). issuetype: ``Bug`` The type of the JIRA ticket. Default: ``Bug``. priority: ``Normal`` The priority of the JIRA ticket. Default: ``Normal``. labels: ``None`` A list of labels to add to the ticket. assignee: ``None`` The name of the person to assign the ticket to. CLI Examples: .. code-block:: bash salt '*' jira.create_issue NET 'Ticket title' 'Ticket description' salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja ''' if template_engine: summary = __salt__['file.apply_template_on_contents'](summary, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) description = __salt__['file.apply_template_on_contents'](description, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) jira_ = _get_jira(server=server, username=username, password=password) if not labels: labels = [] data = { 'project': { 'key': project }, 'summary': summary, 'description': description, 'issuetype': { 'name': issuetype }, 'priority': { 'name': priority }, 'labels': labels } data.update(clean_kwargs(**kwargs)) issue = jira_.create_issue(data) issue_key = str(issue) if assignee: assign_issue(issue_key, assignee) return issue_key def add_comment(issue_key, comment, visibility=None, is_internal=False, server=None, username=None, password=None): ''' Add a comment to an existing ticket. Return ``True`` when it successfully added the comment. issue_key The issue ID to add the comment to. comment The body of the comment to be added. visibility: ``None`` A dictionary having two keys: - ``type``: is ``role`` (or ``group`` if the JIRA server has configured comment visibility for groups). - ``value``: the name of the role (or group) to which viewing of this comment will be restricted. is_internal: ``False`` Whether a comment has to be marked as ``Internal`` in Jira Service Desk. CLI Example: .. code-block:: bash salt '*' jira.add_comment NE-123 'This is a comment' ''' jira_ = _get_jira(server=server, username=username, password=password) comm = jira_.add_comment(issue_key, comment, visibility=visibility, is_internal=is_internal) return True def issue_closed(issue_key, server=None, username=None, password=None): ''' Check if the issue is closed. issue_key The JIRA iD of the ticket to close. Returns: - ``True``: the ticket exists and it is closed. - ``False``: the ticket exists and it has not been closed. - ``None``: the ticket does not exist. CLI Example: .. code-block:: bash salt '*' jira.issue_closed NE-123 ''' if not issue_key: return None jira_ = _get_jira(server=server, username=username, password=password) try: ticket = jira_.issue(issue_key) except jira.exceptions.JIRAError: # Ticket not found return None return ticket.fields().status.name == 'Closed'
saltstack/salt
salt/modules/jira_mod.py
add_comment
python
def add_comment(issue_key, comment, visibility=None, is_internal=False, server=None, username=None, password=None): ''' Add a comment to an existing ticket. Return ``True`` when it successfully added the comment. issue_key The issue ID to add the comment to. comment The body of the comment to be added. visibility: ``None`` A dictionary having two keys: - ``type``: is ``role`` (or ``group`` if the JIRA server has configured comment visibility for groups). - ``value``: the name of the role (or group) to which viewing of this comment will be restricted. is_internal: ``False`` Whether a comment has to be marked as ``Internal`` in Jira Service Desk. CLI Example: .. code-block:: bash salt '*' jira.add_comment NE-123 'This is a comment' ''' jira_ = _get_jira(server=server, username=username, password=password) comm = jira_.add_comment(issue_key, comment, visibility=visibility, is_internal=is_internal) return True
Add a comment to an existing ticket. Return ``True`` when it successfully added the comment. issue_key The issue ID to add the comment to. comment The body of the comment to be added. visibility: ``None`` A dictionary having two keys: - ``type``: is ``role`` (or ``group`` if the JIRA server has configured comment visibility for groups). - ``value``: the name of the role (or group) to which viewing of this comment will be restricted. is_internal: ``False`` Whether a comment has to be marked as ``Internal`` in Jira Service Desk. CLI Example: .. code-block:: bash salt '*' jira.add_comment NE-123 'This is a comment'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L212-L253
[ "def _get_jira(server=None,\n username=None,\n password=None):\n global JIRA\n if not JIRA:\n server, username, password = _get_credentials(server=server,\n username=username,\n password=password)\n JIRA = jira.JIRA(basic_auth=(username, password),\n server=server,\n logging=True) # We want logging\n return JIRA\n" ]
# -*- coding: utf-8 -*- ''' JIRA Execution module ===================== .. versionadded:: 2019.2.0 Execution module to manipulate JIRA tickets via Salt. This module requires the ``jira`` Python library to be installed. Configuration example: .. code-block:: yaml jira: server: https://jira.atlassian.org username: salt password: pass ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging log = logging.getLogger(__name__) # Import salt modules try: from salt.utils import clean_kwargs except ImportError: from salt.utils.args import clean_kwargs # Import third party modules try: import jira HAS_JIRA = True except ImportError: HAS_JIRA = False __virtualname__ = 'jira' __proxyenabled__ = ['*'] JIRA = None def __virtual__(): return __virtualname__ if HAS_JIRA else (False, 'Please install the jira Python libary from PyPI') def _get_credentials(server=None, username=None, password=None): ''' Returns the credentials merged with the config data (opts + pillar). ''' jira_cfg = __salt__['config.merge']('jira', default={}) if not server: server = jira_cfg.get('server') if not username: username = jira_cfg.get('username') if not password: password = jira_cfg.get('password') return server, username, password def _get_jira(server=None, username=None, password=None): global JIRA if not JIRA: server, username, password = _get_credentials(server=server, username=username, password=password) JIRA = jira.JIRA(basic_auth=(username, password), server=server, logging=True) # We want logging return JIRA def create_issue(project, summary, description, template_engine='jinja', context=None, defaults=None, saltenv='base', issuetype='Bug', priority='Normal', labels=None, assignee=None, server=None, username=None, password=None, **kwargs): ''' Create a JIRA issue using the named settings. Return the JIRA ticket ID. project The name of the project to attach the JIRA ticket to. summary The summary (title) of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before creating the ticket. description The full body description of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before creating the ticket. template_engine: ``jinja`` The name of the template engine to be used to render the values of the ``summary`` and ``description`` arguments. Default: ``jinja``. context: ``None`` The context to pass when rendering the ``summary`` and ``description``. This argument is ignored when ``template_engine`` is set as ``None`` defaults: ``None`` Default values to pass to the Salt rendering pipeline for the ``summary`` and ``description`` arguments. This argument is ignored when ``template_engine`` is set as ``None``. saltenv: ``base`` The Salt environment name (for the rendering system). issuetype: ``Bug`` The type of the JIRA ticket. Default: ``Bug``. priority: ``Normal`` The priority of the JIRA ticket. Default: ``Normal``. labels: ``None`` A list of labels to add to the ticket. assignee: ``None`` The name of the person to assign the ticket to. CLI Examples: .. code-block:: bash salt '*' jira.create_issue NET 'Ticket title' 'Ticket description' salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja ''' if template_engine: summary = __salt__['file.apply_template_on_contents'](summary, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) description = __salt__['file.apply_template_on_contents'](description, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) jira_ = _get_jira(server=server, username=username, password=password) if not labels: labels = [] data = { 'project': { 'key': project }, 'summary': summary, 'description': description, 'issuetype': { 'name': issuetype }, 'priority': { 'name': priority }, 'labels': labels } data.update(clean_kwargs(**kwargs)) issue = jira_.create_issue(data) issue_key = str(issue) if assignee: assign_issue(issue_key, assignee) return issue_key def assign_issue(issue_key, assignee, server=None, username=None, password=None): ''' Assign the issue to an existing user. Return ``True`` when the issue has been properly assigned. issue_key The JIRA ID of the ticket to manipulate. assignee The name of the user to assign the ticket to. CLI Example: salt '*' jira.assign_issue NET-123 example_user ''' jira_ = _get_jira(server=server, username=username, password=password) assigned = jira_.assign_issue(issue_key, assignee) return assigned def issue_closed(issue_key, server=None, username=None, password=None): ''' Check if the issue is closed. issue_key The JIRA iD of the ticket to close. Returns: - ``True``: the ticket exists and it is closed. - ``False``: the ticket exists and it has not been closed. - ``None``: the ticket does not exist. CLI Example: .. code-block:: bash salt '*' jira.issue_closed NE-123 ''' if not issue_key: return None jira_ = _get_jira(server=server, username=username, password=password) try: ticket = jira_.issue(issue_key) except jira.exceptions.JIRAError: # Ticket not found return None return ticket.fields().status.name == 'Closed'
saltstack/salt
salt/modules/jira_mod.py
issue_closed
python
def issue_closed(issue_key, server=None, username=None, password=None): ''' Check if the issue is closed. issue_key The JIRA iD of the ticket to close. Returns: - ``True``: the ticket exists and it is closed. - ``False``: the ticket exists and it has not been closed. - ``None``: the ticket does not exist. CLI Example: .. code-block:: bash salt '*' jira.issue_closed NE-123 ''' if not issue_key: return None jira_ = _get_jira(server=server, username=username, password=password) try: ticket = jira_.issue(issue_key) except jira.exceptions.JIRAError: # Ticket not found return None return ticket.fields().status.name == 'Closed'
Check if the issue is closed. issue_key The JIRA iD of the ticket to close. Returns: - ``True``: the ticket exists and it is closed. - ``False``: the ticket exists and it has not been closed. - ``None``: the ticket does not exist. CLI Example: .. code-block:: bash salt '*' jira.issue_closed NE-123
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L256-L288
[ "def _get_jira(server=None,\n username=None,\n password=None):\n global JIRA\n if not JIRA:\n server, username, password = _get_credentials(server=server,\n username=username,\n password=password)\n JIRA = jira.JIRA(basic_auth=(username, password),\n server=server,\n logging=True) # We want logging\n return JIRA\n" ]
# -*- coding: utf-8 -*- ''' JIRA Execution module ===================== .. versionadded:: 2019.2.0 Execution module to manipulate JIRA tickets via Salt. This module requires the ``jira`` Python library to be installed. Configuration example: .. code-block:: yaml jira: server: https://jira.atlassian.org username: salt password: pass ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging log = logging.getLogger(__name__) # Import salt modules try: from salt.utils import clean_kwargs except ImportError: from salt.utils.args import clean_kwargs # Import third party modules try: import jira HAS_JIRA = True except ImportError: HAS_JIRA = False __virtualname__ = 'jira' __proxyenabled__ = ['*'] JIRA = None def __virtual__(): return __virtualname__ if HAS_JIRA else (False, 'Please install the jira Python libary from PyPI') def _get_credentials(server=None, username=None, password=None): ''' Returns the credentials merged with the config data (opts + pillar). ''' jira_cfg = __salt__['config.merge']('jira', default={}) if not server: server = jira_cfg.get('server') if not username: username = jira_cfg.get('username') if not password: password = jira_cfg.get('password') return server, username, password def _get_jira(server=None, username=None, password=None): global JIRA if not JIRA: server, username, password = _get_credentials(server=server, username=username, password=password) JIRA = jira.JIRA(basic_auth=(username, password), server=server, logging=True) # We want logging return JIRA def create_issue(project, summary, description, template_engine='jinja', context=None, defaults=None, saltenv='base', issuetype='Bug', priority='Normal', labels=None, assignee=None, server=None, username=None, password=None, **kwargs): ''' Create a JIRA issue using the named settings. Return the JIRA ticket ID. project The name of the project to attach the JIRA ticket to. summary The summary (title) of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before creating the ticket. description The full body description of the JIRA ticket. When the ``template_engine`` argument is set to a proper value of an existing Salt template engine (e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before creating the ticket. template_engine: ``jinja`` The name of the template engine to be used to render the values of the ``summary`` and ``description`` arguments. Default: ``jinja``. context: ``None`` The context to pass when rendering the ``summary`` and ``description``. This argument is ignored when ``template_engine`` is set as ``None`` defaults: ``None`` Default values to pass to the Salt rendering pipeline for the ``summary`` and ``description`` arguments. This argument is ignored when ``template_engine`` is set as ``None``. saltenv: ``base`` The Salt environment name (for the rendering system). issuetype: ``Bug`` The type of the JIRA ticket. Default: ``Bug``. priority: ``Normal`` The priority of the JIRA ticket. Default: ``Normal``. labels: ``None`` A list of labels to add to the ticket. assignee: ``None`` The name of the person to assign the ticket to. CLI Examples: .. code-block:: bash salt '*' jira.create_issue NET 'Ticket title' 'Ticket description' salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja ''' if template_engine: summary = __salt__['file.apply_template_on_contents'](summary, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) description = __salt__['file.apply_template_on_contents'](description, template=template_engine, context=context, defaults=defaults, saltenv=saltenv) jira_ = _get_jira(server=server, username=username, password=password) if not labels: labels = [] data = { 'project': { 'key': project }, 'summary': summary, 'description': description, 'issuetype': { 'name': issuetype }, 'priority': { 'name': priority }, 'labels': labels } data.update(clean_kwargs(**kwargs)) issue = jira_.create_issue(data) issue_key = str(issue) if assignee: assign_issue(issue_key, assignee) return issue_key def assign_issue(issue_key, assignee, server=None, username=None, password=None): ''' Assign the issue to an existing user. Return ``True`` when the issue has been properly assigned. issue_key The JIRA ID of the ticket to manipulate. assignee The name of the user to assign the ticket to. CLI Example: salt '*' jira.assign_issue NET-123 example_user ''' jira_ = _get_jira(server=server, username=username, password=password) assigned = jira_.assign_issue(issue_key, assignee) return assigned def add_comment(issue_key, comment, visibility=None, is_internal=False, server=None, username=None, password=None): ''' Add a comment to an existing ticket. Return ``True`` when it successfully added the comment. issue_key The issue ID to add the comment to. comment The body of the comment to be added. visibility: ``None`` A dictionary having two keys: - ``type``: is ``role`` (or ``group`` if the JIRA server has configured comment visibility for groups). - ``value``: the name of the role (or group) to which viewing of this comment will be restricted. is_internal: ``False`` Whether a comment has to be marked as ``Internal`` in Jira Service Desk. CLI Example: .. code-block:: bash salt '*' jira.add_comment NE-123 'This is a comment' ''' jira_ = _get_jira(server=server, username=username, password=password) comm = jira_.add_comment(issue_key, comment, visibility=visibility, is_internal=is_internal) return True
saltstack/salt
salt/grains/junos.py
_remove_complex_types
python
def _remove_complex_types(dictionary): ''' Linode-python is now returning some complex types that are not serializable by msgpack. Kill those. ''' for k, v in six.iteritems(dictionary): if isinstance(v, dict): dictionary[k] = _remove_complex_types(v) elif hasattr(v, 'to_eng_string'): dictionary[k] = v.to_eng_string() return dictionary
Linode-python is now returning some complex types that are not serializable by msgpack. Kill those.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/junos.py#L30-L41
null
# -*- coding: utf-8 -*- ''' Grains for junos. NOTE this is a little complicated--junos can only be accessed via salt-proxy-minion.Thus, some grains make sense to get them from the minion (PYTHONPATH), but others don't (ip_interfaces) ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six __proxyenabled__ = ['junos'] __virtualname__ = 'junos' # Get looging started log = logging.getLogger(__name__) def __virtual__(): if 'proxy' not in __opts__: return False else: return __virtualname__ def defaults(): return {'os': 'proxy', 'kernel': 'unknown', 'osrelease': 'proxy'} def facts(proxy=None): if proxy is None or proxy['junos.initialized']() is False: return {} return {'junos_facts': proxy['junos.get_serialized_facts']()} def os_family(): return {'os_family': 'junos'}
saltstack/salt
salt/states/module.py
run
python
def run(**kwargs): ''' Run a single module function or a range of module functions in a batch. Supersedes ``module.run`` function, which requires ``m_`` prefix to function-specific parameters. :param returner: Specify a common returner for the whole batch to send the return data :param kwargs: Pass any arguments needed to execute the function(s) .. code-block:: yaml some_id_of_state: module.run: - network.ip_addrs: - interface: eth0 - cloud.create: - names: - test-isbm-1 - test-isbm-2 - ssh_username: sles - image: sles12sp2 - securitygroup: default - size: 'c3.large' - location: ap-northeast-1 - delvol_on_destroy: True :return: ''' if 'name' in kwargs: kwargs.pop('name') ret = { 'name': list(kwargs), 'changes': {}, 'comment': '', 'result': None, } functions = [func for func in kwargs if '.' in func] missing = [] tests = [] for func in functions: func = func.split(':')[0] if func not in __salt__: missing.append(func) elif __opts__['test']: tests.append(func) if tests or missing: ret['comment'] = ' '.join([ missing and "Unavailable function{plr}: " "{func}.".format(plr=(len(missing) > 1 or ''), func=(', '.join(missing) or '')) or '', tests and "Function{plr} {func} to be " "executed.".format(plr=(len(tests) > 1 or ''), func=(', '.join(tests)) or '') or '', ]).strip() ret['result'] = not (missing or not tests) if ret['result'] is None: ret['result'] = True failures = [] success = [] for func in functions: _func = func.split(':')[0] try: func_ret = _call_function(_func, returner=kwargs.get('returner'), func_args=kwargs.get(func)) if not _get_result(func_ret, ret['changes'].get('ret', {})): if isinstance(func_ret, dict): failures.append("'{0}' failed: {1}".format( func, func_ret.get('comment', '(error message N/A)'))) else: success.append('{0}: {1}'.format( func, func_ret.get('comment', 'Success') if isinstance(func_ret, dict) else func_ret)) ret['changes'][func] = func_ret except (SaltInvocationError, TypeError) as ex: failures.append("'{0}' failed: {1}".format(func, ex)) ret['comment'] = ', '.join(failures + success) ret['result'] = not bool(failures) return ret
Run a single module function or a range of module functions in a batch. Supersedes ``module.run`` function, which requires ``m_`` prefix to function-specific parameters. :param returner: Specify a common returner for the whole batch to send the return data :param kwargs: Pass any arguments needed to execute the function(s) .. code-block:: yaml some_id_of_state: module.run: - network.ip_addrs: - interface: eth0 - cloud.create: - names: - test-isbm-1 - test-isbm-2 - ssh_username: sles - image: sles12sp2 - securitygroup: default - size: 'c3.large' - location: ap-northeast-1 - delvol_on_destroy: True :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/module.py#L350-L436
[ "def _call_function(name, returner=None, **kwargs):\n '''\n Calls a function from the specified module.\n\n :param name:\n :param kwargs:\n :return:\n '''\n argspec = salt.utils.args.get_function_argspec(__salt__[name])\n\n # func_kw is initialized to a dictionary of keyword arguments the function to be run accepts\n func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):], # pylint: disable=incompatible-py3-code\n argspec.defaults or []))\n\n # func_args is initialized to a list of positional arguments that the function to be run accepts\n func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])]\n arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False\n for funcset in reversed(kwargs.get('func_args') or []):\n if not isinstance(funcset, dict):\n # We are just receiving a list of args to the function to be run, so just append\n # those to the arg list that we will pass to the func.\n arg_type.append(funcset)\n else:\n for kwarg_key in six.iterkeys(funcset):\n # We are going to pass in a keyword argument. The trick here is to make certain\n # that if we find that in the *args* list that we pass it there and not as a kwarg\n if kwarg_key in func_args:\n kw_to_arg_type[kwarg_key] = funcset[kwarg_key]\n continue\n else:\n # Otherwise, we're good and just go ahead and pass the keyword/value pair into\n # the kwargs list to be run.\n func_kw.update(funcset)\n arg_type.reverse()\n for arg in func_args:\n if arg in kw_to_arg_type:\n arg_type.append(kw_to_arg_type[arg])\n _exp_prm = len(argspec.args or []) - len(argspec.defaults or [])\n _passed_prm = len(arg_type)\n missing = []\n if na_type and _exp_prm > _passed_prm:\n for arg in argspec.args:\n if arg not in func_kw:\n missing.append(arg)\n if missing:\n raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing)))\n elif _exp_prm > _passed_prm:\n raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format(\n _exp_prm, _passed_prm))\n\n mret = __salt__[name](*arg_type, **func_kw)\n if returner is not None:\n returners = salt.loader.returners(__opts__, __salt__)\n if returner in returners:\n returners[returner]({'id': __opts__['id'], 'ret': mret,\n 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)})\n\n return mret\n", "def _get_result(func_ret, changes):\n res = True\n # if mret is a dict and there is retcode and its non-zero\n if isinstance(func_ret, dict) and func_ret.get('retcode', 0) != 0:\n res = False\n # if its a boolean, return that as the result\n elif isinstance(func_ret, bool):\n res = func_ret\n else:\n changes_ret = changes.get('ret', {})\n if isinstance(changes_ret, dict):\n if isinstance(changes_ret.get('result', {}), bool):\n res = changes_ret.get('result', {})\n elif changes_ret.get('retcode', 0) != 0:\n res = False\n # Explore dict in depth to determine if there is a\n # 'result' key set to False which sets the global\n # state result.\n else:\n res = _get_dict_result(changes_ret)\n\n return res\n" ]
# -*- coding: utf-8 -*- r''' Execution of Salt modules from within states ============================================ .. note:: There are two styles of calling ``module.run``. **The legacy style will no longer be available starting in the Sodium release.** To opt-in early to the new style you must add the following to your ``/etc/salt/minion`` config file: .. code-block:: yaml use_superseded: - module.run With `module.run` these states allow individual execution module calls to be made via states. Here's a contrived example, to show you how it's done: .. code-block:: yaml # New Style test.random_hash: module.run: - test.random_hash: - size: 42 - hash_type: sha256 # Legacy Style test.random_hash: module.run: - size: 42 - hash_type: sha256 In the new style, the state ID (``test.random_hash``, in this case) is irrelevant when using ``module.run``. It could have very well been written: .. code-block:: yaml Generate a random hash: module.run: - test.random_hash: - size: 42 - hash_type: sha256 For a simple state like that it's not a big deal, but if the module you're using has certain parameters, things can get cluttered, fast. Using the contrived custom module (stuck in ``/srv/salt/_modules/foo.py``, or your configured file_roots_): .. code-block:: python def bar(name, names, fun, state, saltenv): return "Name: {name} Names: {names} Fun: {fun} State: {state} Saltenv: {saltenv}".format(**locals()) Your legacy state has to look like this: .. code-block:: yaml # Legacy style Unfortunate example: module.run: - name: foo.bar - m_name: Some name - m_names: - Such names - very wow - m_state: Arkansas - m_fun: Such fun - m_saltenv: Salty With the new style it's much cleaner: .. code-block:: yaml # New style Better: module.run: - foo.bar: - name: Some name - names: - Such names - very wow - state: Arkansas - fun: Such fun - saltenv: Salty The new style also allows multiple modules in one state. For instance, you can do this: .. code-block:: yaml Do many things: module.run: - test.random_hash: - size: 10 - hash_type: md5 # Note the `:` at the end - test.true: - test.arg: - this - has - args - and: kwargs - isn't: that neat? # Note the `:` at the end, too - test.version: - test.fib: - 4 Where in the legacy style you would have had to split your states like this: .. code-block:: yaml test.random_hash: module.run: - size: 10 - hash_type: md5 test.nop: module.run test.arg: module.run: - args: - this - has - args - kwargs: and: kwargs isn't: that neat? test.version: module.run Another difference is that in the legacy style, unconsumed arguments to the ``module`` state were simply passed into the module function being executed: .. code-block:: yaml show off module.run with args: module.run: - name: test.random_hash - size: 42 - hash_type: sha256 The new style is much more explicit, with the arguments and keyword arguments being nested under the name of the function: .. code-block:: yaml show off module.run with args: module.run: # Note the lack of `name: `, and trailing `:` - test.random_hash: - size: 42 - hash_type: sha256 If the function takes ``*args``, they can be passed in as well: .. code-block:: yaml args and kwargs: module.run: - test.arg: - isn't - this - fun - this: that - salt: stack Modern Examples --------------- Here are some other examples using the modern ``module.run``: .. code-block:: yaml fetch_out_of_band: module.run: - git.fetch: - cwd: /path/to/my/repo - user: myuser - opts: '--all' A more complex example: .. code-block:: yaml eventsviewer: module.run: - task.create_task: - name: events-viewer - user_name: System - action_type: Execute - cmd: 'c:\netops\scripts\events_viewer.bat' - trigger_type: 'Daily' - start_date: '2017-1-20' - start_time: '11:59PM' It is sometimes desirable to trigger a function call after a state is executed, for this the :mod:`module.wait <salt.states.module.wait>` state can be used: .. code-block:: yaml add example to hosts: file.append: - name: /etc/hosts - text: 203.0.113.13 example.com # New Style mine.send: module.wait: # Again, note the trailing `:` - hosts.list_hosts: - watch: - file: add example to hosts Legacy (Default) Examples ------------------------- If you're using the legacy ``module.run``, due to how the state system works, if a module function accepts an argument called, ``name``, then ``m_name`` must be used to specify that argument, to avoid a collision with the ``name`` argument. Here is a list of keywords hidden by the state system, which must be prefixed with ``m_``: * fun * name * names * state * saltenv For example: .. code-block:: yaml disable_nfs: module.run: - name: service.disable - m_name: nfs Note that some modules read all or some of the arguments from a list of keyword arguments. For example: .. code-block:: yaml mine.send: module.run: - func: network.ip_addrs - kwargs: interface: eth0 .. code-block:: yaml cloud.create: module.run: - func: cloud.create - provider: test-provider - m_names: - test-vlad - kwargs: { ssh_username: 'ubuntu', image: 'ami-8d6d9daa', securitygroup: 'default', size: 'c3.large', location: 'ap-northeast-1', delvol_on_destroy: 'True' } Other modules take the keyword arguments using this style: .. code-block:: yaml mac_enable_ssh: module.run: - name: system.set_remote_login - enable: True Another example that creates a recurring task that runs a batch file on a Windows system: .. code-block:: yaml eventsviewer: module.run: - name: task.create_task - m_name: 'events-viewer' - user_name: System - kwargs: { action_type: 'Execute', cmd: 'c:\netops\scripts\events_viewer.bat', trigger_type: 'Daily', start_date: '2017-1-20', start_time: '11:59PM' } .. _file_roots: https://docs.saltstack.com/en/latest/ref/configuration/master.html#file-roots ''' from __future__ import absolute_import, print_function, unicode_literals # Import salt libs import salt.loader import salt.utils.args import salt.utils.functools import salt.utils.jid from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves import zip from salt.exceptions import SaltInvocationError from salt.utils.decorators import with_deprecated def wait(name, **kwargs): ''' Run a single module function only if the watch statement calls it ``name`` The module function to execute ``**kwargs`` Pass any arguments needed to execute the function .. note:: Like the :mod:`cmd.run <salt.states.cmd.run>` state, this state will return ``True`` but not actually execute, unless one of the following two things happens: 1. The state has a :ref:`watch requisite <requisites-watch>`, and the state which it is watching changes. 2. Another state has a :ref:`watch_in requisite <requisites-watch-in>` which references this state, and the state wth the ``watch_in`` changes. ''' return {'name': name, 'changes': {}, 'result': True, 'comment': ''} # Alias module.watch to module.wait watch = salt.utils.functools.alias_function(wait, 'watch') @with_deprecated(globals(), "Sodium", policy=with_deprecated.OPT_IN) def _call_function(name, returner=None, **kwargs): ''' Calls a function from the specified module. :param name: :param kwargs: :return: ''' argspec = salt.utils.args.get_function_argspec(__salt__[name]) # func_kw is initialized to a dictionary of keyword arguments the function to be run accepts func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):], # pylint: disable=incompatible-py3-code argspec.defaults or [])) # func_args is initialized to a list of positional arguments that the function to be run accepts func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])] arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False for funcset in reversed(kwargs.get('func_args') or []): if not isinstance(funcset, dict): # We are just receiving a list of args to the function to be run, so just append # those to the arg list that we will pass to the func. arg_type.append(funcset) else: for kwarg_key in six.iterkeys(funcset): # We are going to pass in a keyword argument. The trick here is to make certain # that if we find that in the *args* list that we pass it there and not as a kwarg if kwarg_key in func_args: kw_to_arg_type[kwarg_key] = funcset[kwarg_key] continue else: # Otherwise, we're good and just go ahead and pass the keyword/value pair into # the kwargs list to be run. func_kw.update(funcset) arg_type.reverse() for arg in func_args: if arg in kw_to_arg_type: arg_type.append(kw_to_arg_type[arg]) _exp_prm = len(argspec.args or []) - len(argspec.defaults or []) _passed_prm = len(arg_type) missing = [] if na_type and _exp_prm > _passed_prm: for arg in argspec.args: if arg not in func_kw: missing.append(arg) if missing: raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing))) elif _exp_prm > _passed_prm: raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format( _exp_prm, _passed_prm)) mret = __salt__[name](*arg_type, **func_kw) if returner is not None: returners = salt.loader.returners(__opts__, __salt__) if returner in returners: returners[returner]({'id': __opts__['id'], 'ret': mret, 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)}) return mret def _run(name, **kwargs): ''' .. deprecated:: 2017.7.0 Function name stays the same, behaviour will change. Run a single module function ``name`` The module function to execute ``returner`` Specify the returner to send the return of the module execution to ``kwargs`` Pass any arguments needed to execute the function ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': None} if name not in __salt__: ret['comment'] = 'Module function {0} is not available'.format(name) ret['result'] = False return ret if __opts__['test']: ret['comment'] = 'Module function {0} is set to execute'.format(name) return ret aspec = salt.utils.args.get_function_argspec(__salt__[name]) args = [] defaults = {} arglen = 0 deflen = 0 if isinstance(aspec.args, list): arglen = len(aspec.args) if isinstance(aspec.defaults, tuple): deflen = len(aspec.defaults) # Match up the defaults with the respective args for ind in range(arglen - 1, -1, -1): minus = arglen - ind if deflen - minus > -1: defaults[aspec.args[ind]] = aspec.defaults[-minus] # overwrite passed default kwargs for arg in defaults: if arg == 'name': if 'm_name' in kwargs: defaults[arg] = kwargs.pop('m_name') elif arg == 'fun': if 'm_fun' in kwargs: defaults[arg] = kwargs.pop('m_fun') elif arg == 'state': if 'm_state' in kwargs: defaults[arg] = kwargs.pop('m_state') elif arg == 'saltenv': if 'm_saltenv' in kwargs: defaults[arg] = kwargs.pop('m_saltenv') if arg in kwargs: defaults[arg] = kwargs.pop(arg) missing = set() for arg in aspec.args: if arg == 'name': rarg = 'm_name' elif arg == 'fun': rarg = 'm_fun' elif arg == 'names': rarg = 'm_names' elif arg == 'state': rarg = 'm_state' elif arg == 'saltenv': rarg = 'm_saltenv' else: rarg = arg if rarg not in kwargs and arg not in defaults: missing.add(rarg) continue if arg in defaults: args.append(defaults[arg]) else: args.append(kwargs.pop(rarg)) if missing: comment = 'The following arguments are missing:' for arg in missing: comment += ' {0}'.format(arg) ret['comment'] = comment ret['result'] = False return ret if aspec.varargs: if aspec.varargs == 'name': rarg = 'm_name' elif aspec.varargs == 'fun': rarg = 'm_fun' elif aspec.varargs == 'names': rarg = 'm_names' elif aspec.varargs == 'state': rarg = 'm_state' elif aspec.varargs == 'saltenv': rarg = 'm_saltenv' else: rarg = aspec.varargs if rarg in kwargs: varargs = kwargs.pop(rarg) if not isinstance(varargs, list): msg = "'{0}' must be a list." ret['comment'] = msg.format(aspec.varargs) ret['result'] = False return ret args.extend(varargs) nkwargs = {} if aspec.keywords and aspec.keywords in kwargs: nkwargs = kwargs.pop(aspec.keywords) if not isinstance(nkwargs, dict): msg = "'{0}' must be a dict." ret['comment'] = msg.format(aspec.keywords) ret['result'] = False return ret try: if aspec.keywords: mret = __salt__[name](*args, **nkwargs) else: mret = __salt__[name](*args) except Exception as e: ret['comment'] = 'Module function {0} threw an exception. Exception: {1}'.format(name, e) ret['result'] = False return ret else: if mret is not None or mret is not {}: ret['changes']['ret'] = mret if 'returner' in kwargs: ret_ret = { 'id': __opts__['id'], 'ret': mret, 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)} returners = salt.loader.returners(__opts__, __salt__) if kwargs['returner'] in returners: returners[kwargs['returner']](ret_ret) ret['comment'] = 'Module function {0} executed'.format(name) ret['result'] = _get_result(mret, ret['changes']) return ret def _get_result(func_ret, changes): res = True # if mret is a dict and there is retcode and its non-zero if isinstance(func_ret, dict) and func_ret.get('retcode', 0) != 0: res = False # if its a boolean, return that as the result elif isinstance(func_ret, bool): res = func_ret else: changes_ret = changes.get('ret', {}) if isinstance(changes_ret, dict): if isinstance(changes_ret.get('result', {}), bool): res = changes_ret.get('result', {}) elif changes_ret.get('retcode', 0) != 0: res = False # Explore dict in depth to determine if there is a # 'result' key set to False which sets the global # state result. else: res = _get_dict_result(changes_ret) return res def _get_dict_result(node): ret = True for key, val in six.iteritems(node): if key == 'result' and val is False: ret = False break elif isinstance(val, dict): ret = _get_dict_result(val) if ret is False: break return ret mod_watch = salt.utils.functools.alias_function(run, 'mod_watch')
saltstack/salt
salt/states/module.py
_call_function
python
def _call_function(name, returner=None, **kwargs): ''' Calls a function from the specified module. :param name: :param kwargs: :return: ''' argspec = salt.utils.args.get_function_argspec(__salt__[name]) # func_kw is initialized to a dictionary of keyword arguments the function to be run accepts func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):], # pylint: disable=incompatible-py3-code argspec.defaults or [])) # func_args is initialized to a list of positional arguments that the function to be run accepts func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])] arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False for funcset in reversed(kwargs.get('func_args') or []): if not isinstance(funcset, dict): # We are just receiving a list of args to the function to be run, so just append # those to the arg list that we will pass to the func. arg_type.append(funcset) else: for kwarg_key in six.iterkeys(funcset): # We are going to pass in a keyword argument. The trick here is to make certain # that if we find that in the *args* list that we pass it there and not as a kwarg if kwarg_key in func_args: kw_to_arg_type[kwarg_key] = funcset[kwarg_key] continue else: # Otherwise, we're good and just go ahead and pass the keyword/value pair into # the kwargs list to be run. func_kw.update(funcset) arg_type.reverse() for arg in func_args: if arg in kw_to_arg_type: arg_type.append(kw_to_arg_type[arg]) _exp_prm = len(argspec.args or []) - len(argspec.defaults or []) _passed_prm = len(arg_type) missing = [] if na_type and _exp_prm > _passed_prm: for arg in argspec.args: if arg not in func_kw: missing.append(arg) if missing: raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing))) elif _exp_prm > _passed_prm: raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format( _exp_prm, _passed_prm)) mret = __salt__[name](*arg_type, **func_kw) if returner is not None: returners = salt.loader.returners(__opts__, __salt__) if returner in returners: returners[returner]({'id': __opts__['id'], 'ret': mret, 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)}) return mret
Calls a function from the specified module. :param name: :param kwargs: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/module.py#L439-L496
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def get_function_argspec(func, is_class_method=None):\n '''\n A small wrapper around getargspec that also supports callable classes\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n '''\n if not callable(func):\n raise TypeError('{0} is not a callable'.format(func))\n\n if six.PY2:\n if is_class_method is True:\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = inspect.getargspec(func)\n elif inspect.ismethod(func):\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = inspect.getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n else:\n if is_class_method is True:\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = _getargspec(func) # pylint: disable=redefined-variable-type\n elif inspect.ismethod(func):\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = _getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n return aspec\n" ]
# -*- coding: utf-8 -*- r''' Execution of Salt modules from within states ============================================ .. note:: There are two styles of calling ``module.run``. **The legacy style will no longer be available starting in the Sodium release.** To opt-in early to the new style you must add the following to your ``/etc/salt/minion`` config file: .. code-block:: yaml use_superseded: - module.run With `module.run` these states allow individual execution module calls to be made via states. Here's a contrived example, to show you how it's done: .. code-block:: yaml # New Style test.random_hash: module.run: - test.random_hash: - size: 42 - hash_type: sha256 # Legacy Style test.random_hash: module.run: - size: 42 - hash_type: sha256 In the new style, the state ID (``test.random_hash``, in this case) is irrelevant when using ``module.run``. It could have very well been written: .. code-block:: yaml Generate a random hash: module.run: - test.random_hash: - size: 42 - hash_type: sha256 For a simple state like that it's not a big deal, but if the module you're using has certain parameters, things can get cluttered, fast. Using the contrived custom module (stuck in ``/srv/salt/_modules/foo.py``, or your configured file_roots_): .. code-block:: python def bar(name, names, fun, state, saltenv): return "Name: {name} Names: {names} Fun: {fun} State: {state} Saltenv: {saltenv}".format(**locals()) Your legacy state has to look like this: .. code-block:: yaml # Legacy style Unfortunate example: module.run: - name: foo.bar - m_name: Some name - m_names: - Such names - very wow - m_state: Arkansas - m_fun: Such fun - m_saltenv: Salty With the new style it's much cleaner: .. code-block:: yaml # New style Better: module.run: - foo.bar: - name: Some name - names: - Such names - very wow - state: Arkansas - fun: Such fun - saltenv: Salty The new style also allows multiple modules in one state. For instance, you can do this: .. code-block:: yaml Do many things: module.run: - test.random_hash: - size: 10 - hash_type: md5 # Note the `:` at the end - test.true: - test.arg: - this - has - args - and: kwargs - isn't: that neat? # Note the `:` at the end, too - test.version: - test.fib: - 4 Where in the legacy style you would have had to split your states like this: .. code-block:: yaml test.random_hash: module.run: - size: 10 - hash_type: md5 test.nop: module.run test.arg: module.run: - args: - this - has - args - kwargs: and: kwargs isn't: that neat? test.version: module.run Another difference is that in the legacy style, unconsumed arguments to the ``module`` state were simply passed into the module function being executed: .. code-block:: yaml show off module.run with args: module.run: - name: test.random_hash - size: 42 - hash_type: sha256 The new style is much more explicit, with the arguments and keyword arguments being nested under the name of the function: .. code-block:: yaml show off module.run with args: module.run: # Note the lack of `name: `, and trailing `:` - test.random_hash: - size: 42 - hash_type: sha256 If the function takes ``*args``, they can be passed in as well: .. code-block:: yaml args and kwargs: module.run: - test.arg: - isn't - this - fun - this: that - salt: stack Modern Examples --------------- Here are some other examples using the modern ``module.run``: .. code-block:: yaml fetch_out_of_band: module.run: - git.fetch: - cwd: /path/to/my/repo - user: myuser - opts: '--all' A more complex example: .. code-block:: yaml eventsviewer: module.run: - task.create_task: - name: events-viewer - user_name: System - action_type: Execute - cmd: 'c:\netops\scripts\events_viewer.bat' - trigger_type: 'Daily' - start_date: '2017-1-20' - start_time: '11:59PM' It is sometimes desirable to trigger a function call after a state is executed, for this the :mod:`module.wait <salt.states.module.wait>` state can be used: .. code-block:: yaml add example to hosts: file.append: - name: /etc/hosts - text: 203.0.113.13 example.com # New Style mine.send: module.wait: # Again, note the trailing `:` - hosts.list_hosts: - watch: - file: add example to hosts Legacy (Default) Examples ------------------------- If you're using the legacy ``module.run``, due to how the state system works, if a module function accepts an argument called, ``name``, then ``m_name`` must be used to specify that argument, to avoid a collision with the ``name`` argument. Here is a list of keywords hidden by the state system, which must be prefixed with ``m_``: * fun * name * names * state * saltenv For example: .. code-block:: yaml disable_nfs: module.run: - name: service.disable - m_name: nfs Note that some modules read all or some of the arguments from a list of keyword arguments. For example: .. code-block:: yaml mine.send: module.run: - func: network.ip_addrs - kwargs: interface: eth0 .. code-block:: yaml cloud.create: module.run: - func: cloud.create - provider: test-provider - m_names: - test-vlad - kwargs: { ssh_username: 'ubuntu', image: 'ami-8d6d9daa', securitygroup: 'default', size: 'c3.large', location: 'ap-northeast-1', delvol_on_destroy: 'True' } Other modules take the keyword arguments using this style: .. code-block:: yaml mac_enable_ssh: module.run: - name: system.set_remote_login - enable: True Another example that creates a recurring task that runs a batch file on a Windows system: .. code-block:: yaml eventsviewer: module.run: - name: task.create_task - m_name: 'events-viewer' - user_name: System - kwargs: { action_type: 'Execute', cmd: 'c:\netops\scripts\events_viewer.bat', trigger_type: 'Daily', start_date: '2017-1-20', start_time: '11:59PM' } .. _file_roots: https://docs.saltstack.com/en/latest/ref/configuration/master.html#file-roots ''' from __future__ import absolute_import, print_function, unicode_literals # Import salt libs import salt.loader import salt.utils.args import salt.utils.functools import salt.utils.jid from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves import zip from salt.exceptions import SaltInvocationError from salt.utils.decorators import with_deprecated def wait(name, **kwargs): ''' Run a single module function only if the watch statement calls it ``name`` The module function to execute ``**kwargs`` Pass any arguments needed to execute the function .. note:: Like the :mod:`cmd.run <salt.states.cmd.run>` state, this state will return ``True`` but not actually execute, unless one of the following two things happens: 1. The state has a :ref:`watch requisite <requisites-watch>`, and the state which it is watching changes. 2. Another state has a :ref:`watch_in requisite <requisites-watch-in>` which references this state, and the state wth the ``watch_in`` changes. ''' return {'name': name, 'changes': {}, 'result': True, 'comment': ''} # Alias module.watch to module.wait watch = salt.utils.functools.alias_function(wait, 'watch') @with_deprecated(globals(), "Sodium", policy=with_deprecated.OPT_IN) def run(**kwargs): ''' Run a single module function or a range of module functions in a batch. Supersedes ``module.run`` function, which requires ``m_`` prefix to function-specific parameters. :param returner: Specify a common returner for the whole batch to send the return data :param kwargs: Pass any arguments needed to execute the function(s) .. code-block:: yaml some_id_of_state: module.run: - network.ip_addrs: - interface: eth0 - cloud.create: - names: - test-isbm-1 - test-isbm-2 - ssh_username: sles - image: sles12sp2 - securitygroup: default - size: 'c3.large' - location: ap-northeast-1 - delvol_on_destroy: True :return: ''' if 'name' in kwargs: kwargs.pop('name') ret = { 'name': list(kwargs), 'changes': {}, 'comment': '', 'result': None, } functions = [func for func in kwargs if '.' in func] missing = [] tests = [] for func in functions: func = func.split(':')[0] if func not in __salt__: missing.append(func) elif __opts__['test']: tests.append(func) if tests or missing: ret['comment'] = ' '.join([ missing and "Unavailable function{plr}: " "{func}.".format(plr=(len(missing) > 1 or ''), func=(', '.join(missing) or '')) or '', tests and "Function{plr} {func} to be " "executed.".format(plr=(len(tests) > 1 or ''), func=(', '.join(tests)) or '') or '', ]).strip() ret['result'] = not (missing or not tests) if ret['result'] is None: ret['result'] = True failures = [] success = [] for func in functions: _func = func.split(':')[0] try: func_ret = _call_function(_func, returner=kwargs.get('returner'), func_args=kwargs.get(func)) if not _get_result(func_ret, ret['changes'].get('ret', {})): if isinstance(func_ret, dict): failures.append("'{0}' failed: {1}".format( func, func_ret.get('comment', '(error message N/A)'))) else: success.append('{0}: {1}'.format( func, func_ret.get('comment', 'Success') if isinstance(func_ret, dict) else func_ret)) ret['changes'][func] = func_ret except (SaltInvocationError, TypeError) as ex: failures.append("'{0}' failed: {1}".format(func, ex)) ret['comment'] = ', '.join(failures + success) ret['result'] = not bool(failures) return ret def _run(name, **kwargs): ''' .. deprecated:: 2017.7.0 Function name stays the same, behaviour will change. Run a single module function ``name`` The module function to execute ``returner`` Specify the returner to send the return of the module execution to ``kwargs`` Pass any arguments needed to execute the function ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': None} if name not in __salt__: ret['comment'] = 'Module function {0} is not available'.format(name) ret['result'] = False return ret if __opts__['test']: ret['comment'] = 'Module function {0} is set to execute'.format(name) return ret aspec = salt.utils.args.get_function_argspec(__salt__[name]) args = [] defaults = {} arglen = 0 deflen = 0 if isinstance(aspec.args, list): arglen = len(aspec.args) if isinstance(aspec.defaults, tuple): deflen = len(aspec.defaults) # Match up the defaults with the respective args for ind in range(arglen - 1, -1, -1): minus = arglen - ind if deflen - minus > -1: defaults[aspec.args[ind]] = aspec.defaults[-minus] # overwrite passed default kwargs for arg in defaults: if arg == 'name': if 'm_name' in kwargs: defaults[arg] = kwargs.pop('m_name') elif arg == 'fun': if 'm_fun' in kwargs: defaults[arg] = kwargs.pop('m_fun') elif arg == 'state': if 'm_state' in kwargs: defaults[arg] = kwargs.pop('m_state') elif arg == 'saltenv': if 'm_saltenv' in kwargs: defaults[arg] = kwargs.pop('m_saltenv') if arg in kwargs: defaults[arg] = kwargs.pop(arg) missing = set() for arg in aspec.args: if arg == 'name': rarg = 'm_name' elif arg == 'fun': rarg = 'm_fun' elif arg == 'names': rarg = 'm_names' elif arg == 'state': rarg = 'm_state' elif arg == 'saltenv': rarg = 'm_saltenv' else: rarg = arg if rarg not in kwargs and arg not in defaults: missing.add(rarg) continue if arg in defaults: args.append(defaults[arg]) else: args.append(kwargs.pop(rarg)) if missing: comment = 'The following arguments are missing:' for arg in missing: comment += ' {0}'.format(arg) ret['comment'] = comment ret['result'] = False return ret if aspec.varargs: if aspec.varargs == 'name': rarg = 'm_name' elif aspec.varargs == 'fun': rarg = 'm_fun' elif aspec.varargs == 'names': rarg = 'm_names' elif aspec.varargs == 'state': rarg = 'm_state' elif aspec.varargs == 'saltenv': rarg = 'm_saltenv' else: rarg = aspec.varargs if rarg in kwargs: varargs = kwargs.pop(rarg) if not isinstance(varargs, list): msg = "'{0}' must be a list." ret['comment'] = msg.format(aspec.varargs) ret['result'] = False return ret args.extend(varargs) nkwargs = {} if aspec.keywords and aspec.keywords in kwargs: nkwargs = kwargs.pop(aspec.keywords) if not isinstance(nkwargs, dict): msg = "'{0}' must be a dict." ret['comment'] = msg.format(aspec.keywords) ret['result'] = False return ret try: if aspec.keywords: mret = __salt__[name](*args, **nkwargs) else: mret = __salt__[name](*args) except Exception as e: ret['comment'] = 'Module function {0} threw an exception. Exception: {1}'.format(name, e) ret['result'] = False return ret else: if mret is not None or mret is not {}: ret['changes']['ret'] = mret if 'returner' in kwargs: ret_ret = { 'id': __opts__['id'], 'ret': mret, 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)} returners = salt.loader.returners(__opts__, __salt__) if kwargs['returner'] in returners: returners[kwargs['returner']](ret_ret) ret['comment'] = 'Module function {0} executed'.format(name) ret['result'] = _get_result(mret, ret['changes']) return ret def _get_result(func_ret, changes): res = True # if mret is a dict and there is retcode and its non-zero if isinstance(func_ret, dict) and func_ret.get('retcode', 0) != 0: res = False # if its a boolean, return that as the result elif isinstance(func_ret, bool): res = func_ret else: changes_ret = changes.get('ret', {}) if isinstance(changes_ret, dict): if isinstance(changes_ret.get('result', {}), bool): res = changes_ret.get('result', {}) elif changes_ret.get('retcode', 0) != 0: res = False # Explore dict in depth to determine if there is a # 'result' key set to False which sets the global # state result. else: res = _get_dict_result(changes_ret) return res def _get_dict_result(node): ret = True for key, val in six.iteritems(node): if key == 'result' and val is False: ret = False break elif isinstance(val, dict): ret = _get_dict_result(val) if ret is False: break return ret mod_watch = salt.utils.functools.alias_function(run, 'mod_watch')
saltstack/salt
salt/states/module.py
_run
python
def _run(name, **kwargs): ''' .. deprecated:: 2017.7.0 Function name stays the same, behaviour will change. Run a single module function ``name`` The module function to execute ``returner`` Specify the returner to send the return of the module execution to ``kwargs`` Pass any arguments needed to execute the function ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': None} if name not in __salt__: ret['comment'] = 'Module function {0} is not available'.format(name) ret['result'] = False return ret if __opts__['test']: ret['comment'] = 'Module function {0} is set to execute'.format(name) return ret aspec = salt.utils.args.get_function_argspec(__salt__[name]) args = [] defaults = {} arglen = 0 deflen = 0 if isinstance(aspec.args, list): arglen = len(aspec.args) if isinstance(aspec.defaults, tuple): deflen = len(aspec.defaults) # Match up the defaults with the respective args for ind in range(arglen - 1, -1, -1): minus = arglen - ind if deflen - minus > -1: defaults[aspec.args[ind]] = aspec.defaults[-minus] # overwrite passed default kwargs for arg in defaults: if arg == 'name': if 'm_name' in kwargs: defaults[arg] = kwargs.pop('m_name') elif arg == 'fun': if 'm_fun' in kwargs: defaults[arg] = kwargs.pop('m_fun') elif arg == 'state': if 'm_state' in kwargs: defaults[arg] = kwargs.pop('m_state') elif arg == 'saltenv': if 'm_saltenv' in kwargs: defaults[arg] = kwargs.pop('m_saltenv') if arg in kwargs: defaults[arg] = kwargs.pop(arg) missing = set() for arg in aspec.args: if arg == 'name': rarg = 'm_name' elif arg == 'fun': rarg = 'm_fun' elif arg == 'names': rarg = 'm_names' elif arg == 'state': rarg = 'm_state' elif arg == 'saltenv': rarg = 'm_saltenv' else: rarg = arg if rarg not in kwargs and arg not in defaults: missing.add(rarg) continue if arg in defaults: args.append(defaults[arg]) else: args.append(kwargs.pop(rarg)) if missing: comment = 'The following arguments are missing:' for arg in missing: comment += ' {0}'.format(arg) ret['comment'] = comment ret['result'] = False return ret if aspec.varargs: if aspec.varargs == 'name': rarg = 'm_name' elif aspec.varargs == 'fun': rarg = 'm_fun' elif aspec.varargs == 'names': rarg = 'm_names' elif aspec.varargs == 'state': rarg = 'm_state' elif aspec.varargs == 'saltenv': rarg = 'm_saltenv' else: rarg = aspec.varargs if rarg in kwargs: varargs = kwargs.pop(rarg) if not isinstance(varargs, list): msg = "'{0}' must be a list." ret['comment'] = msg.format(aspec.varargs) ret['result'] = False return ret args.extend(varargs) nkwargs = {} if aspec.keywords and aspec.keywords in kwargs: nkwargs = kwargs.pop(aspec.keywords) if not isinstance(nkwargs, dict): msg = "'{0}' must be a dict." ret['comment'] = msg.format(aspec.keywords) ret['result'] = False return ret try: if aspec.keywords: mret = __salt__[name](*args, **nkwargs) else: mret = __salt__[name](*args) except Exception as e: ret['comment'] = 'Module function {0} threw an exception. Exception: {1}'.format(name, e) ret['result'] = False return ret else: if mret is not None or mret is not {}: ret['changes']['ret'] = mret if 'returner' in kwargs: ret_ret = { 'id': __opts__['id'], 'ret': mret, 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)} returners = salt.loader.returners(__opts__, __salt__) if kwargs['returner'] in returners: returners[kwargs['returner']](ret_ret) ret['comment'] = 'Module function {0} executed'.format(name) ret['result'] = _get_result(mret, ret['changes']) return ret
.. deprecated:: 2017.7.0 Function name stays the same, behaviour will change. Run a single module function ``name`` The module function to execute ``returner`` Specify the returner to send the return of the module execution to ``kwargs`` Pass any arguments needed to execute the function
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/module.py#L499-L647
[ "def get_function_argspec(func, is_class_method=None):\n '''\n A small wrapper around getargspec that also supports callable classes\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n '''\n if not callable(func):\n raise TypeError('{0} is not a callable'.format(func))\n\n if six.PY2:\n if is_class_method is True:\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = inspect.getargspec(func)\n elif inspect.ismethod(func):\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = inspect.getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n else:\n if is_class_method is True:\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = _getargspec(func) # pylint: disable=redefined-variable-type\n elif inspect.ismethod(func):\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = _getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n return aspec\n", "def gen_jid(opts=None):\n '''\n Generate a jid\n '''\n if opts is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). '\n 'This will be required starting in {version}.'\n )\n opts = {}\n global LAST_JID_DATETIME # pylint: disable=global-statement\n\n if opts.get('utc_jid', False):\n jid_dt = datetime.datetime.utcnow()\n else:\n jid_dt = datetime.datetime.now()\n if not opts.get('unique_jid', False):\n return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt)\n if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt:\n jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1)\n LAST_JID_DATETIME = jid_dt\n return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid())\n", "def _get_result(func_ret, changes):\n res = True\n # if mret is a dict and there is retcode and its non-zero\n if isinstance(func_ret, dict) and func_ret.get('retcode', 0) != 0:\n res = False\n # if its a boolean, return that as the result\n elif isinstance(func_ret, bool):\n res = func_ret\n else:\n changes_ret = changes.get('ret', {})\n if isinstance(changes_ret, dict):\n if isinstance(changes_ret.get('result', {}), bool):\n res = changes_ret.get('result', {})\n elif changes_ret.get('retcode', 0) != 0:\n res = False\n # Explore dict in depth to determine if there is a\n # 'result' key set to False which sets the global\n # state result.\n else:\n res = _get_dict_result(changes_ret)\n\n return res\n" ]
# -*- coding: utf-8 -*- r''' Execution of Salt modules from within states ============================================ .. note:: There are two styles of calling ``module.run``. **The legacy style will no longer be available starting in the Sodium release.** To opt-in early to the new style you must add the following to your ``/etc/salt/minion`` config file: .. code-block:: yaml use_superseded: - module.run With `module.run` these states allow individual execution module calls to be made via states. Here's a contrived example, to show you how it's done: .. code-block:: yaml # New Style test.random_hash: module.run: - test.random_hash: - size: 42 - hash_type: sha256 # Legacy Style test.random_hash: module.run: - size: 42 - hash_type: sha256 In the new style, the state ID (``test.random_hash``, in this case) is irrelevant when using ``module.run``. It could have very well been written: .. code-block:: yaml Generate a random hash: module.run: - test.random_hash: - size: 42 - hash_type: sha256 For a simple state like that it's not a big deal, but if the module you're using has certain parameters, things can get cluttered, fast. Using the contrived custom module (stuck in ``/srv/salt/_modules/foo.py``, or your configured file_roots_): .. code-block:: python def bar(name, names, fun, state, saltenv): return "Name: {name} Names: {names} Fun: {fun} State: {state} Saltenv: {saltenv}".format(**locals()) Your legacy state has to look like this: .. code-block:: yaml # Legacy style Unfortunate example: module.run: - name: foo.bar - m_name: Some name - m_names: - Such names - very wow - m_state: Arkansas - m_fun: Such fun - m_saltenv: Salty With the new style it's much cleaner: .. code-block:: yaml # New style Better: module.run: - foo.bar: - name: Some name - names: - Such names - very wow - state: Arkansas - fun: Such fun - saltenv: Salty The new style also allows multiple modules in one state. For instance, you can do this: .. code-block:: yaml Do many things: module.run: - test.random_hash: - size: 10 - hash_type: md5 # Note the `:` at the end - test.true: - test.arg: - this - has - args - and: kwargs - isn't: that neat? # Note the `:` at the end, too - test.version: - test.fib: - 4 Where in the legacy style you would have had to split your states like this: .. code-block:: yaml test.random_hash: module.run: - size: 10 - hash_type: md5 test.nop: module.run test.arg: module.run: - args: - this - has - args - kwargs: and: kwargs isn't: that neat? test.version: module.run Another difference is that in the legacy style, unconsumed arguments to the ``module`` state were simply passed into the module function being executed: .. code-block:: yaml show off module.run with args: module.run: - name: test.random_hash - size: 42 - hash_type: sha256 The new style is much more explicit, with the arguments and keyword arguments being nested under the name of the function: .. code-block:: yaml show off module.run with args: module.run: # Note the lack of `name: `, and trailing `:` - test.random_hash: - size: 42 - hash_type: sha256 If the function takes ``*args``, they can be passed in as well: .. code-block:: yaml args and kwargs: module.run: - test.arg: - isn't - this - fun - this: that - salt: stack Modern Examples --------------- Here are some other examples using the modern ``module.run``: .. code-block:: yaml fetch_out_of_band: module.run: - git.fetch: - cwd: /path/to/my/repo - user: myuser - opts: '--all' A more complex example: .. code-block:: yaml eventsviewer: module.run: - task.create_task: - name: events-viewer - user_name: System - action_type: Execute - cmd: 'c:\netops\scripts\events_viewer.bat' - trigger_type: 'Daily' - start_date: '2017-1-20' - start_time: '11:59PM' It is sometimes desirable to trigger a function call after a state is executed, for this the :mod:`module.wait <salt.states.module.wait>` state can be used: .. code-block:: yaml add example to hosts: file.append: - name: /etc/hosts - text: 203.0.113.13 example.com # New Style mine.send: module.wait: # Again, note the trailing `:` - hosts.list_hosts: - watch: - file: add example to hosts Legacy (Default) Examples ------------------------- If you're using the legacy ``module.run``, due to how the state system works, if a module function accepts an argument called, ``name``, then ``m_name`` must be used to specify that argument, to avoid a collision with the ``name`` argument. Here is a list of keywords hidden by the state system, which must be prefixed with ``m_``: * fun * name * names * state * saltenv For example: .. code-block:: yaml disable_nfs: module.run: - name: service.disable - m_name: nfs Note that some modules read all or some of the arguments from a list of keyword arguments. For example: .. code-block:: yaml mine.send: module.run: - func: network.ip_addrs - kwargs: interface: eth0 .. code-block:: yaml cloud.create: module.run: - func: cloud.create - provider: test-provider - m_names: - test-vlad - kwargs: { ssh_username: 'ubuntu', image: 'ami-8d6d9daa', securitygroup: 'default', size: 'c3.large', location: 'ap-northeast-1', delvol_on_destroy: 'True' } Other modules take the keyword arguments using this style: .. code-block:: yaml mac_enable_ssh: module.run: - name: system.set_remote_login - enable: True Another example that creates a recurring task that runs a batch file on a Windows system: .. code-block:: yaml eventsviewer: module.run: - name: task.create_task - m_name: 'events-viewer' - user_name: System - kwargs: { action_type: 'Execute', cmd: 'c:\netops\scripts\events_viewer.bat', trigger_type: 'Daily', start_date: '2017-1-20', start_time: '11:59PM' } .. _file_roots: https://docs.saltstack.com/en/latest/ref/configuration/master.html#file-roots ''' from __future__ import absolute_import, print_function, unicode_literals # Import salt libs import salt.loader import salt.utils.args import salt.utils.functools import salt.utils.jid from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves import zip from salt.exceptions import SaltInvocationError from salt.utils.decorators import with_deprecated def wait(name, **kwargs): ''' Run a single module function only if the watch statement calls it ``name`` The module function to execute ``**kwargs`` Pass any arguments needed to execute the function .. note:: Like the :mod:`cmd.run <salt.states.cmd.run>` state, this state will return ``True`` but not actually execute, unless one of the following two things happens: 1. The state has a :ref:`watch requisite <requisites-watch>`, and the state which it is watching changes. 2. Another state has a :ref:`watch_in requisite <requisites-watch-in>` which references this state, and the state wth the ``watch_in`` changes. ''' return {'name': name, 'changes': {}, 'result': True, 'comment': ''} # Alias module.watch to module.wait watch = salt.utils.functools.alias_function(wait, 'watch') @with_deprecated(globals(), "Sodium", policy=with_deprecated.OPT_IN) def run(**kwargs): ''' Run a single module function or a range of module functions in a batch. Supersedes ``module.run`` function, which requires ``m_`` prefix to function-specific parameters. :param returner: Specify a common returner for the whole batch to send the return data :param kwargs: Pass any arguments needed to execute the function(s) .. code-block:: yaml some_id_of_state: module.run: - network.ip_addrs: - interface: eth0 - cloud.create: - names: - test-isbm-1 - test-isbm-2 - ssh_username: sles - image: sles12sp2 - securitygroup: default - size: 'c3.large' - location: ap-northeast-1 - delvol_on_destroy: True :return: ''' if 'name' in kwargs: kwargs.pop('name') ret = { 'name': list(kwargs), 'changes': {}, 'comment': '', 'result': None, } functions = [func for func in kwargs if '.' in func] missing = [] tests = [] for func in functions: func = func.split(':')[0] if func not in __salt__: missing.append(func) elif __opts__['test']: tests.append(func) if tests or missing: ret['comment'] = ' '.join([ missing and "Unavailable function{plr}: " "{func}.".format(plr=(len(missing) > 1 or ''), func=(', '.join(missing) or '')) or '', tests and "Function{plr} {func} to be " "executed.".format(plr=(len(tests) > 1 or ''), func=(', '.join(tests)) or '') or '', ]).strip() ret['result'] = not (missing or not tests) if ret['result'] is None: ret['result'] = True failures = [] success = [] for func in functions: _func = func.split(':')[0] try: func_ret = _call_function(_func, returner=kwargs.get('returner'), func_args=kwargs.get(func)) if not _get_result(func_ret, ret['changes'].get('ret', {})): if isinstance(func_ret, dict): failures.append("'{0}' failed: {1}".format( func, func_ret.get('comment', '(error message N/A)'))) else: success.append('{0}: {1}'.format( func, func_ret.get('comment', 'Success') if isinstance(func_ret, dict) else func_ret)) ret['changes'][func] = func_ret except (SaltInvocationError, TypeError) as ex: failures.append("'{0}' failed: {1}".format(func, ex)) ret['comment'] = ', '.join(failures + success) ret['result'] = not bool(failures) return ret def _call_function(name, returner=None, **kwargs): ''' Calls a function from the specified module. :param name: :param kwargs: :return: ''' argspec = salt.utils.args.get_function_argspec(__salt__[name]) # func_kw is initialized to a dictionary of keyword arguments the function to be run accepts func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):], # pylint: disable=incompatible-py3-code argspec.defaults or [])) # func_args is initialized to a list of positional arguments that the function to be run accepts func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])] arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False for funcset in reversed(kwargs.get('func_args') or []): if not isinstance(funcset, dict): # We are just receiving a list of args to the function to be run, so just append # those to the arg list that we will pass to the func. arg_type.append(funcset) else: for kwarg_key in six.iterkeys(funcset): # We are going to pass in a keyword argument. The trick here is to make certain # that if we find that in the *args* list that we pass it there and not as a kwarg if kwarg_key in func_args: kw_to_arg_type[kwarg_key] = funcset[kwarg_key] continue else: # Otherwise, we're good and just go ahead and pass the keyword/value pair into # the kwargs list to be run. func_kw.update(funcset) arg_type.reverse() for arg in func_args: if arg in kw_to_arg_type: arg_type.append(kw_to_arg_type[arg]) _exp_prm = len(argspec.args or []) - len(argspec.defaults or []) _passed_prm = len(arg_type) missing = [] if na_type and _exp_prm > _passed_prm: for arg in argspec.args: if arg not in func_kw: missing.append(arg) if missing: raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing))) elif _exp_prm > _passed_prm: raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format( _exp_prm, _passed_prm)) mret = __salt__[name](*arg_type, **func_kw) if returner is not None: returners = salt.loader.returners(__opts__, __salt__) if returner in returners: returners[returner]({'id': __opts__['id'], 'ret': mret, 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)}) return mret def _get_result(func_ret, changes): res = True # if mret is a dict and there is retcode and its non-zero if isinstance(func_ret, dict) and func_ret.get('retcode', 0) != 0: res = False # if its a boolean, return that as the result elif isinstance(func_ret, bool): res = func_ret else: changes_ret = changes.get('ret', {}) if isinstance(changes_ret, dict): if isinstance(changes_ret.get('result', {}), bool): res = changes_ret.get('result', {}) elif changes_ret.get('retcode', 0) != 0: res = False # Explore dict in depth to determine if there is a # 'result' key set to False which sets the global # state result. else: res = _get_dict_result(changes_ret) return res def _get_dict_result(node): ret = True for key, val in six.iteritems(node): if key == 'result' and val is False: ret = False break elif isinstance(val, dict): ret = _get_dict_result(val) if ret is False: break return ret mod_watch = salt.utils.functools.alias_function(run, 'mod_watch')
saltstack/salt
salt/matchers/list_match.py
match
python
def match(tgt, opts=None): ''' Determines if this host is on the list ''' if not opts: opts = __opts__ try: if ',' + opts['id'] + ',' in tgt \ or tgt.startswith(opts['id'] + ',') \ or tgt.endswith(',' + opts['id']): return True # tgt is a string, which we know because the if statement above did not # cause one of the exceptions being caught. Therefore, look for an # exact match. (e.g. salt -L foo test.ping) return opts['id'] == tgt except (AttributeError, TypeError): # tgt is not a string, maybe it's a sequence type? try: return opts['id'] in tgt except Exception: # tgt was likely some invalid type return False # We should never get here based on the return statements in the logic # above. If we do, it is because something above changed, and should be # considered as a bug. Log a warning to help us catch this. log.warning( 'List matcher unexpectedly did not return, for target %s, ' 'this is probably a bug.', tgt ) return False
Determines if this host is on the list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/list_match.py#L11-L42
null
# -*- coding: utf-8 -*- ''' This is the default list matcher. ''' from __future__ import absolute_import, print_function, unicode_literals import logging log = logging.getLogger(__name__)
saltstack/salt
salt/modules/influxdb08mod.py
db_list
python
def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database()
List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L65-L90
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
db_exists
python
def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs]
Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L93-L122
[ "def db_list(user=None, password=None, host=None, port=None):\n '''\n List all InfluxDB databases\n\n user\n The user to connect as\n\n password\n The password of the user\n\n host\n The host to connect to\n\n port\n The port to connect to\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' influxdb08.db_list\n salt '*' influxdb08.db_list <user> <password> <host> <port>\n\n '''\n client = _client(user=user, password=password, host=host, port=port)\n return client.get_list_database()\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
db_create
python
def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True
Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L125-L156
[ "def db_exists(name, user=None, password=None, host=None, port=None):\n '''\n Checks if a database exists in Influxdb\n\n name\n Database name to create\n\n user\n The user to connect as\n\n password\n The password of the user\n\n host\n The host to connect to\n\n port\n The port to connect to\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' influxdb08.db_exists <name>\n salt '*' influxdb08.db_exists <name> <user> <password> <host> <port>\n '''\n dbs = db_list(user, password, host, port)\n if not isinstance(dbs, list):\n return False\n return name in [db['name'] for db in dbs]\n", "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
db_remove
python
def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name)
Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L159-L189
[ "def db_exists(name, user=None, password=None, host=None, port=None):\n '''\n Checks if a database exists in Influxdb\n\n name\n Database name to create\n\n user\n The user to connect as\n\n password\n The password of the user\n\n host\n The host to connect to\n\n port\n The port to connect to\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' influxdb08.db_exists <name>\n salt '*' influxdb08.db_exists <name> <user> <password> <host> <port>\n '''\n dbs = db_list(user, password, host, port)\n if not isinstance(dbs, list):\n return False\n return name in [db['name'] for db in dbs]\n", "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
user_list
python
def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users()
List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L192-L228
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
user_exists
python
def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False
Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L231-L277
[ "def user_list(database=None, user=None, password=None, host=None, port=None):\n '''\n List cluster admins or database users.\n\n If a database is specified: it will return database users list.\n If a database is not specified: it will return cluster admins list.\n\n database\n The database to list the users from\n\n user\n The user to connect as\n\n password\n The password of the user\n\n host\n The host to connect to\n\n port\n The port to connect to\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' influxdb08.user_list\n salt '*' influxdb08.user_list <database>\n salt '*' influxdb08.user_list <database> <user> <password> <host> <port>\n '''\n client = _client(user=user, password=password, host=host, port=port)\n\n if not database:\n return client.get_list_cluster_admins()\n\n client.switch_database(database)\n return client.get_list_users()\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
user_create
python
def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd)
Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L280-L335
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n", "def user_exists(name, database=None, user=None, password=None, host=None, port=None):\n '''\n Checks if a cluster admin or database user exists.\n\n If a database is specified: it will check for database user existence.\n If a database is not specified: it will check for cluster admin existence.\n\n name\n User name\n\n database\n The database to check for the user to exist\n\n user\n The user to connect as\n\n password\n The password of the user\n\n host\n The host to connect to\n\n port\n The port to connect to\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' influxdb08.user_exists <name>\n salt '*' influxdb08.user_exists <name> <database>\n salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port>\n '''\n users = user_list(database, user, password, host, port)\n if not isinstance(users, list):\n return False\n\n for user in users:\n # the dict key could be different depending on influxdb version\n username = user.get('user', user.get('name'))\n if username:\n if username == name:\n return True\n else:\n log.warning('Could not find username in user: %s', user)\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
user_chpass
python
def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd)
Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L338-L393
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n", "def user_exists(name, database=None, user=None, password=None, host=None, port=None):\n '''\n Checks if a cluster admin or database user exists.\n\n If a database is specified: it will check for database user existence.\n If a database is not specified: it will check for cluster admin existence.\n\n name\n User name\n\n database\n The database to check for the user to exist\n\n user\n The user to connect as\n\n password\n The password of the user\n\n host\n The host to connect to\n\n port\n The port to connect to\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' influxdb08.user_exists <name>\n salt '*' influxdb08.user_exists <name> <database>\n salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port>\n '''\n users = user_list(database, user, password, host, port)\n if not isinstance(users, list):\n return False\n\n for user in users:\n # the dict key could be different depending on influxdb version\n username = user.get('user', user.get('name'))\n if username:\n if username == name:\n return True\n else:\n log.warning('Could not find username in user: %s', user)\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
user_remove
python
def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name)
Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L396-L450
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n", "def user_exists(name, database=None, user=None, password=None, host=None, port=None):\n '''\n Checks if a cluster admin or database user exists.\n\n If a database is specified: it will check for database user existence.\n If a database is not specified: it will check for cluster admin existence.\n\n name\n User name\n\n database\n The database to check for the user to exist\n\n user\n The user to connect as\n\n password\n The password of the user\n\n host\n The host to connect to\n\n port\n The port to connect to\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' influxdb08.user_exists <name>\n salt '*' influxdb08.user_exists <name> <database>\n salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port>\n '''\n users = user_list(database, user, password, host, port)\n if not isinstance(users, list):\n return False\n\n for user in users:\n # the dict key could be different depending on influxdb version\n username = user.get('user', user.get('name'))\n if username:\n if username == name:\n return True\n else:\n log.warning('Could not find username in user: %s', user)\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
retention_policy_get
python
def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None
Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L453-L480
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
retention_policy_exists
python
def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None
Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L483-L505
[ "def retention_policy_get(database,\n name,\n user=None,\n password=None,\n host=None,\n port=None):\n '''\n Get an existing retention policy.\n\n database\n The database to operate on.\n\n name\n Name of the policy to modify.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' influxdb08.retention_policy_get metrics default\n '''\n client = _client(user=user, password=password, host=host, port=port)\n\n for policy in client.get_list_retention_policies(database):\n if policy['name'] == name:\n return policy\n\n return None\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
retention_policy_add
python
def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True
Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L508-L543
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
retention_policy_alter
python
def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True
Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L546-L581
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked) def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/modules/influxdb08mod.py
query
python
def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) client.switch_database(database) return client.query(query, time_precision=time_precision, chunked=chunked)
Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.query <database> <query> salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L584-L628
[ "def _client(user=None, password=None, host=None, port=None):\n if not user:\n user = __salt__['config.option']('influxdb08.user', 'root')\n if not password:\n password = __salt__['config.option']('influxdb08.password', 'root')\n if not host:\n host = __salt__['config.option']('influxdb08.host', 'localhost')\n if not port:\n port = __salt__['config.option']('influxdb08.port', 8086)\n return influxdb.influxdb08.InfluxDBClient(\n host=host, port=port, username=user, password=password)\n" ]
# -*- coding: utf-8 -*- ''' InfluxDB - A distributed time series database Module to provide InfluxDB compatibility to Salt (compatible with InfluxDB version 0.5-0.8) .. versionadded:: 2014.7.0 :depends: - influxdb Python module (>= 1.0.0) :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: influxdb08.host: 'localhost' influxdb08.port: 8086 influxdb08.user: 'root' influxdb08.password: 'root' This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals try: import influxdb.influxdb08 HAS_INFLUXDB_08 = True except ImportError: HAS_INFLUXDB_08 = False import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'influxdb08' def __virtual__(): ''' Only load if influxdb lib is present ''' if HAS_INFLUXDB_08: return __virtualname__ return (False, 'The influx execution module cannot be loaded: influxdb library not available.') def _client(user=None, password=None, host=None, port=None): if not user: user = __salt__['config.option']('influxdb08.user', 'root') if not password: password = __salt__['config.option']('influxdb08.password', 'root') if not host: host = __salt__['config.option']('influxdb08.host', 'localhost') if not port: port = __salt__['config.option']('influxdb08.port', 8086) return influxdb.influxdb08.InfluxDBClient( host=host, port=port, username=user, password=password) def db_list(user=None, password=None, host=None, port=None): ''' List all InfluxDB databases user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_list salt '*' influxdb08.db_list <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) return client.get_list_database() def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_exists <name> salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port) if not isinstance(dbs, list): return False return name in [db['name'] for db in dbs] def db_create(name, user=None, password=None, host=None, port=None): ''' Create a database name Database name to create user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_create <name> salt '*' influxdb08.db_create <name> <user> <password> <host> <port> ''' if db_exists(name, user, password, host, port): log.info('DB \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) client.create_database(name) return True def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> ''' if not db_exists(name, user, password, host, port): log.info('DB \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) return client.delete_database(name) def user_list(database=None, user=None, password=None, host=None, port=None): ''' List cluster admins or database users. If a database is specified: it will return database users list. If a database is not specified: it will return cluster admins list. database The database to list the users from user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_list salt '*' influxdb08.user_list <database> salt '*' influxdb08.user_list <database> <user> <password> <host> <port> ''' client = _client(user=user, password=password, host=host, port=port) if not database: return client.get_list_cluster_admins() client.switch_database(database) return client.get_list_users() def user_exists(name, database=None, user=None, password=None, host=None, port=None): ''' Checks if a cluster admin or database user exists. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name User name database The database to check for the user to exist user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_exists <name> salt '*' influxdb08.user_exists <name> <database> salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> ''' users = user_list(database, user, password, host, port) if not isinstance(users, list): return False for user in users: # the dict key could be different depending on influxdb version username = user.get('user', user.get('name')) if username: if username == name: return True else: log.warning('Could not find username in user: %s', user) return False def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a database is not specified: it will create a cluster admin. name User name for the new user to create passwd Password for the new user to create database The database to create the user in user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_create <name> <passwd> salt '*' influxdb08.user_create <name> <passwd> <database> salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> ''' if user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' already exists for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' already exists', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.add_cluster_admin(name, passwd) client.switch_database(database) return client.add_database_user(name, passwd) def user_chpass(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Change password for a cluster admin or a database user. If a database is specified: it will update database user password. If a database is not specified: it will update cluster admin password. name User name for whom to change the password passwd New password database The database on which to operate user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_chpass <name> <passwd> salt '*' influxdb08.user_chpass <name> <passwd> <database> salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.update_cluster_admin_password(name, passwd) client.switch_database(database) return client.update_database_user_password(name, passwd) def user_remove(name, database=None, user=None, password=None, host=None, port=None): ''' Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove database The database to remove the user from user User name for the new user to delete user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.user_remove <name> salt '*' influxdb08.user_remove <name> <database> salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> ''' if not user_exists(name, database, user, password, host, port): if database: log.info('User \'%s\' does not exist for DB \'%s\'', name, database) else: log.info('Cluster admin \'%s\' does not exist', name) return False client = _client(user=user, password=password, host=host, port=port) if not database: return client.delete_cluster_admin(name) client.switch_database(database) return client.delete_database_user(name) def retention_policy_get(database, name, user=None, password=None, host=None, port=None): ''' Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default ''' client = _client(user=user, password=password, host=host, port=port) for policy in client.get_list_retention_policies(database): if policy['name'] == name: return policy return None def retention_policy_exists(database, name, user=None, password=None, host=None, port=None): ''' Check if a retention policy exists. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_exists metrics default ''' policy = retention_policy_get(database, name, user, password, host, port) return policy is not None def retention_policy_add(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Add a retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb.retention_policy_add metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.create_retention_policy(name, duration, replication, database, default) return True def retention_policy_alter(database, name, duration, replication, default=False, user=None, password=None, host=None, port=None): ''' Modify an existing retention policy. database The database to operate on. name Name of the policy to modify. duration How long InfluxDB keeps the data. replication How many copies of the data are stored in the cluster. default Whether this policy should be the default or not. Default is False. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_modify metrics default 1d 1 ''' client = _client(user=user, password=password, host=host, port=port) client.alter_retention_policy(name, database, duration, replication, default) return True def login_test(name, password, database=None, host=None, port=None): ''' Checks if a credential pair can log in at all. If a database is specified: it will check for database user existence. If a database is not specified: it will check for cluster admin existence. name The user to connect as password The password of the user database The database to try to log in to host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.login_test <name> salt '*' influxdb08.login_test <name> <database> salt '*' influxdb08.login_test <name> <database> <user> <password> <host> <port> ''' try: client = _client(user=name, password=password, host=host, port=port) client.get_list_database() return True except influxdb.influxdb08.client.InfluxDBClientError as e: if e.code == 401: return False else: raise
saltstack/salt
salt/log/handlers/__init__.py
TemporaryLoggingHandler.sync_with_handlers
python
def sync_with_handlers(self, handlers=()): ''' Sync the stored log records to the provided log handlers. ''' if not handlers: return while self.__messages: record = self.__messages.pop(0) for handler in handlers: if handler.level > record.levelno: # If the handler's level is higher than the log record one, # it should not handle the log record continue handler.handle(record)
Sync the stored log records to the provided log handlers.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/__init__.py#L73-L87
null
class TemporaryLoggingHandler(logging.NullHandler): ''' This logging handler will store all the log records up to its maximum queue size at which stage the first messages stored will be dropped. Should only be used as a temporary logging handler, while the logging system is not fully configured. Once configured, pass any logging handlers that should have received the initial log messages to the function :func:`TemporaryLoggingHandler.sync_with_handlers` and all stored log records will be dispatched to the provided handlers. .. versionadded:: 0.17.0 ''' def __init__(self, level=logging.NOTSET, max_queue_size=10000): self.__max_queue_size = max_queue_size super(TemporaryLoggingHandler, self).__init__(level=level) self.__messages = [] def handle(self, record): self.acquire() if len(self.__messages) >= self.__max_queue_size: # Loose the initial log records self.__messages.pop(0) self.__messages.append(record) self.release()
saltstack/salt
salt/log/handlers/__init__.py
SysLogHandler.handleError
python
def handleError(self, record): ''' Override the default error handling mechanism for py3 Deal with syslog os errors when the log file does not exist ''' handled = False if sys.stderr and sys.version_info >= (3, 5, 4): t, v, tb = sys.exc_info() if t.__name__ in 'FileNotFoundError': sys.stderr.write('[WARNING ] The log_file does not exist. Logging not setup correctly or syslog service not started.\n') handled = True if not handled: super(SysLogHandler, self).handleError(record)
Override the default error handling mechanism for py3 Deal with syslog os errors when the log file does not exist
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/__init__.py#L106-L119
null
class SysLogHandler(ExcInfoOnLogLevelFormatMixIn, logging.handlers.SysLogHandler, NewStyleClassMixIn): ''' Syslog handler which properly handles exc_info on a per handler basis '''
saltstack/salt
salt/log/handlers/__init__.py
RotatingFileHandler.handleError
python
def handleError(self, record): ''' Override the default error handling mechanism Deal with log file rotation errors due to log file in use more softly. ''' handled = False # Can't use "salt.utils.platform.is_windows()" in this file if (sys.platform.startswith('win') and logging.raiseExceptions and sys.stderr): # see Python issue 13807 exc_type, exc, exc_traceback = sys.exc_info() try: # PermissionError is used since Python 3.3. # OSError is used for previous versions of Python. if exc_type.__name__ in ('PermissionError', 'OSError') and exc.winerror == 32: if self.level <= logging.WARNING: sys.stderr.write('[WARNING ] Unable to rotate the log file "{0}" ' 'because it is in use\n'.format(self.baseFilename) ) handled = True finally: # 'del' recommended. See documentation of # 'sys.exc_info()' for details. del exc_type, exc, exc_traceback if not handled: super(RotatingFileHandler, self).handleError(record)
Override the default error handling mechanism Deal with log file rotation errors due to log file in use more softly.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/__init__.py#L126-L155
null
class RotatingFileHandler(ExcInfoOnLogLevelFormatMixIn, logging.handlers.RotatingFileHandler, NewStyleClassMixIn): ''' Rotating file handler which properly handles exc_info on a per handler basis '''
saltstack/salt
salt/beacons/status.py
beacon
python
def beacon(config): ''' Return status for requested information ''' log.debug(config) ctime = datetime.datetime.utcnow().isoformat() if not config: config = [{ 'loadavg': ['all'], 'cpustats': ['all'], 'meminfo': ['all'], 'vmstats': ['all'], 'time': ['all'], }] if not isinstance(config, list): # To support the old dictionary config format config = [config] ret = {} for entry in config: for func in entry: ret[func] = {} try: data = __salt__['status.{0}'.format(func)]() except salt.exceptions.CommandExecutionError as exc: log.debug('Status beacon attempted to process function %s ' 'but encountered error: %s', func, exc) continue if not isinstance(entry[func], list): func_items = [entry[func]] else: func_items = entry[func] for item in func_items: if item == 'all': ret[func] = data else: try: try: ret[func][item] = data[item] except TypeError: ret[func][item] = data[int(item)] except KeyError as exc: ret[func] = 'Status beacon is incorrectly configured: {0}'.format(exc) return [{ 'tag': ctime, 'data': ret, }]
Return status for requested information
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/status.py#L119-L168
null
# -*- coding: utf-8 -*- ''' The status beacon is intended to send a basic health check event up to the master, this allows for event driven routines based on presence to be set up. The intention of this beacon is to add the config options to add monitoring stats to the health beacon making it a one stop shop for gathering systems health and status data .. versionadded:: 2016.11.0 To configure this beacon to use the defaults, set up an empty dict for it in the minion config: .. code-block:: yaml beacons: status: [] By default, all of the information from the following execution module functions will be returned: - loadavg - cpustats - meminfo - vmstats - time You can also configure your own set of functions to be returned: .. code-block:: yaml beacons: status: - time: - all - loadavg: - all You may also configure only certain fields from each function to be returned. For instance, the ``loadavg`` function returns the following fields: - 1-min - 5-min - 15-min If you wanted to return only the ``1-min`` and ``5-min`` fields for ``loadavg`` then you would configure: .. code-block:: yaml beacons: status: - loadavg: - 1-min - 5-min Other functions only return a single value instead of a dictionary. With these, you may specify ``all`` or ``0``. The following are both valid: .. code-block:: yaml beacons: status: - time: - all beacons: status: - time: - 0 If a ``status`` function returns a list, you may return the index marker or markers for specific list items: .. code-block:: yaml beacons: status: - w: - 0 - 1 - 2 .. warning:: Not all status functions are supported for every operating system. Be certain to check the minion log for errors after configuring this beacon. ''' # Import python libs from __future__ import absolute_import, unicode_literals import logging import datetime import salt.exceptions # Import salt libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'status' def validate(config): ''' Validate the the config is a dict ''' if not isinstance(config, list): return False, ('Configuration for status beacon must be a list.') return True, 'Valid beacon configuration' def __virtual__(): return __virtualname__
saltstack/salt
salt/states/sysctl.py
present
python
def present(name, value, config=None): ''' Ensure that the named sysctl value is set in memory and persisted to the named configuration file. The default sysctl configuration file is /etc/sysctl.conf name The name of the sysctl value to edit value The sysctl value to apply config The location of the sysctl configuration file. If not specified, the proper location will be detected based on platform. ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} if config is None: # Certain linux systems will ignore /etc/sysctl.conf, get the right # default configuration file. if 'sysctl.default_config' in __salt__: config = __salt__['sysctl.default_config']() else: config = '/etc/sysctl.conf' if __opts__['test']: current = __salt__['sysctl.show']() configured = __salt__['sysctl.show'](config_file=config) if configured is None: ret['result'] = None ret['comment'] = ( 'Sysctl option {0} might be changed, we failed to check ' 'config file at {1}. The file is either unreadable, or ' 'missing.'.format(name, config) ) return ret if name in current and name not in configured: if re.sub(' +|\t+', ' ', current[name]) != \ re.sub(' +|\t+', ' ', six.text_type(value)): ret['result'] = None ret['comment'] = ( 'Sysctl option {0} set to be changed to {1}' .format(name, value) ) return ret else: ret['result'] = None ret['comment'] = ( 'Sysctl value is currently set on the running system but ' 'not in a config file. Sysctl option {0} set to be ' 'changed to {1} in config file.'.format(name, value) ) return ret elif name in configured and name not in current: ret['result'] = None ret['comment'] = ( 'Sysctl value {0} is present in configuration file but is not ' 'present in the running config. The value {0} is set to be ' 'changed to {1}'.format(name, value) ) return ret elif name in configured and name in current: if six.text_type(value).split() == __salt__['sysctl.get'](name).split(): ret['result'] = True ret['comment'] = ( 'Sysctl value {0} = {1} is already set' .format(name, value) ) return ret # otherwise, we don't have it set anywhere and need to set it ret['result'] = None ret['comment'] = ( 'Sysctl option {0} would be changed to {1}'.format(name, value) ) return ret try: update = __salt__['sysctl.persist'](name, value, config) except CommandExecutionError as exc: ret['result'] = False ret['comment'] = ( 'Failed to set {0} to {1}: {2}'.format(name, value, exc) ) return ret if update == 'Updated': ret['changes'] = {name: value} ret['comment'] = 'Updated sysctl value {0} = {1}'.format(name, value) elif update == 'Already set': ret['comment'] = ( 'Sysctl value {0} = {1} is already set' .format(name, value) ) return ret
Ensure that the named sysctl value is set in memory and persisted to the named configuration file. The default sysctl configuration file is /etc/sysctl.conf name The name of the sysctl value to edit value The sysctl value to apply config The location of the sysctl configuration file. If not specified, the proper location will be detected based on platform.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sysctl.py#L33-L131
null
# -*- coding: utf-8 -*- ''' Configuration of the kernel using sysctl ======================================== Control the kernel sysctl system. .. code-block:: yaml vm.swappiness: sysctl.present: - value: 20 ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re # Import salt libs from salt.exceptions import CommandExecutionError # Import 3rd part libs from salt.ext import six def __virtual__(): ''' This state is only available on Minions which support sysctl ''' return 'sysctl.show' in __salt__
saltstack/salt
salt/grains/opts.py
opts
python
def opts(): ''' Return the minion configuration settings ''' if __opts__.get('grain_opts', False) or \ (isinstance(__pillar__, dict) and __pillar__.get('grain_opts', False)): return __opts__ return {}
Return the minion configuration settings
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/opts.py#L9-L16
null
# -*- coding: utf-8 -*- ''' Simple grain to merge the opts into the grains directly if the grain_opts configuration value is set ''' from __future__ import absolute_import, print_function, unicode_literals
saltstack/salt
salt/modules/freebsd_update.py
_cmd
python
def _cmd(**kwargs): ''' .. versionadded:: 2016.3.4 Private function that returns the freebsd-update command string to be executed. It checks if any arguments are given to freebsd-update and appends them accordingly. ''' update_cmd = salt.utils.path.which('freebsd-update') if not update_cmd: raise CommandNotFoundError('"freebsd-update" command not found') params = [] if 'basedir' in kwargs: params.append('-b {0}'.format(kwargs['basedir'])) if 'workdir' in kwargs: params.append('-d {0}'.format(kwargs['workdir'])) if 'conffile' in kwargs: params.append('-f {0}'.format(kwargs['conffile'])) if 'force' in kwargs: params.append('-F') if 'key' in kwargs: params.append('-k {0}'.format(kwargs['key'])) if 'newrelease' in kwargs: params.append('-r {0}'.format(kwargs['newrelease'])) if 'server' in kwargs: params.append('-s {0}'.format(kwargs['server'])) if 'address' in kwargs: params.append('-t {0}'.format(kwargs['address'])) if params: return '{0} {1}'.format(update_cmd, ' '.join(params)) return update_cmd
.. versionadded:: 2016.3.4 Private function that returns the freebsd-update command string to be executed. It checks if any arguments are given to freebsd-update and appends them accordingly.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_update.py#L45-L77
null
# -*- coding: utf-8 -*- ''' Support for freebsd-update utility on FreeBSD. .. versionadded:: 2017.7.0 :maintainer: George Mamalakis <mamalos@gmail.com> :maturity: new :platform: FreeBSD ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging # Import salt libs import salt.utils.path from salt.ext import six from salt.exceptions import CommandNotFoundError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'freebsd_update' __virtual_aliases__ = ('freebsd-update',) def __virtual__(): ''' .. versionadded:: 2016.3.4 Only work on FreeBSD RELEASEs >= 6.2, where freebsd-update was introduced. ''' if __grains__['os'] != 'FreeBSD': return (False, 'The freebsd_update execution module cannot be loaded: only available on FreeBSD systems.') if float(__grains__['osrelease']) < 6.2: return (False, 'freebsd_update is only available on FreeBSD versions >= 6.2-RELESE') if 'release' not in __grains__['kernelrelease'].lower(): return (False, 'freebsd_update is only available on FreeBSD RELEASES') return __virtualname__ def _wrapper(orig, pre='', post='', err_=None, run_args=None, **kwargs): ''' Helper function that wraps the execution of freebsd-update command. orig: Originating function that called _wrapper(). pre: String that will be prepended to freebsd-update command. post: String that will be appended to freebsd-update command. err_: Dictionary on which return codes and stout/stderr are copied. run_args: Arguments to be passed on cmd.run_all. kwargs: Parameters of freebsd-update command. ''' ret = '' # the message to be returned cmd = _cmd(**kwargs) cmd_str = ' '.join([x for x in (pre, cmd, post, orig)]) if run_args and isinstance(run_args, dict): res = __salt__['cmd.run_all'](cmd_str, **run_args) else: res = __salt__['cmd.run_all'](cmd_str) if isinstance(err_, dict): # copy return values if asked to for k, v in six.itermitems(res): err_[k] = v if 'retcode' in res and res['retcode'] != 0: msg = ' '.join([x for x in (res['stdout'], res['stderr']) if x]) ret = 'Unable to run "{0}" with run_args="{1}". Error: {2}'.format(cmd_str, run_args, msg) log.error(ret) else: try: ret = res['stdout'] except KeyError: log.error("cmd.run_all did not return a dictionary with a key named 'stdout'") return ret def fetch(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update fetch wrapper. Based on the currently installed world and the configuration options set, fetch all available binary updates. kwargs: Parameters of freebsd-update command. ''' # fetch continues when no controlling terminal is present pre = '' post = '' run_args = {} if float(__grains__['osrelease']) >= 10.2: post += '--not-running-from-cron' else: pre += ' env PAGER=cat' run_args['python_shell'] = True return _wrapper('fetch', pre=pre, post=post, run_args=run_args, **kwargs) def install(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update install wrapper. Install the most recently fetched updates or upgrade. kwargs: Parameters of freebsd-update command. ''' return _wrapper('install', **kwargs) def rollback(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update rollback wrapper. Uninstalls the most recently installed updates. kwargs: Parameters of freebsd-update command. ''' return _wrapper('rollback', **kwargs) def update(**kwargs): ''' .. versionadded:: 2016.3.4 Command that simplifies freebsd-update by running freebsd-update fetch first and then freebsd-update install. kwargs: Parameters of freebsd-update command. ''' stdout = {} for mode in ('fetch', 'install'): err_ = {} ret = _wrapper(mode, err_=err_, **kwargs) if 'retcode' in err_ and err_['retcode'] != 0: return ret if 'stdout' in err_: stdout[mode] = err_['stdout'] return '\n'.join(['{0}: {1}'.format(k, v) for (k, v) in six.iteritems(stdout)]) def ids(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update IDS wrapper function. Compares the system against a "known good" index of the installed release. kwargs: Parameters of freebsd-update command. ''' return _wrapper('IDS', **kwargs) def upgrade(**kwargs): ''' .. versionadded:: 2016.3.4 Dummy function used only to print a message that upgrade is not available. The reason is that upgrade needs manual intervention and reboot, so even if used with: yes | freebsd-upgrade -r VERSION the additional freebsd-update install that needs to run after the reboot cannot be implemented easily. kwargs: Parameters of freebsd-update command. ''' msg = 'freebsd-update upgrade not yet implemented.' log.warning(msg) return msg
saltstack/salt
salt/modules/freebsd_update.py
_wrapper
python
def _wrapper(orig, pre='', post='', err_=None, run_args=None, **kwargs): ''' Helper function that wraps the execution of freebsd-update command. orig: Originating function that called _wrapper(). pre: String that will be prepended to freebsd-update command. post: String that will be appended to freebsd-update command. err_: Dictionary on which return codes and stout/stderr are copied. run_args: Arguments to be passed on cmd.run_all. kwargs: Parameters of freebsd-update command. ''' ret = '' # the message to be returned cmd = _cmd(**kwargs) cmd_str = ' '.join([x for x in (pre, cmd, post, orig)]) if run_args and isinstance(run_args, dict): res = __salt__['cmd.run_all'](cmd_str, **run_args) else: res = __salt__['cmd.run_all'](cmd_str) if isinstance(err_, dict): # copy return values if asked to for k, v in six.itermitems(res): err_[k] = v if 'retcode' in res and res['retcode'] != 0: msg = ' '.join([x for x in (res['stdout'], res['stderr']) if x]) ret = 'Unable to run "{0}" with run_args="{1}". Error: {2}'.format(cmd_str, run_args, msg) log.error(ret) else: try: ret = res['stdout'] except KeyError: log.error("cmd.run_all did not return a dictionary with a key named 'stdout'") return ret
Helper function that wraps the execution of freebsd-update command. orig: Originating function that called _wrapper(). pre: String that will be prepended to freebsd-update command. post: String that will be appended to freebsd-update command. err_: Dictionary on which return codes and stout/stderr are copied. run_args: Arguments to be passed on cmd.run_all. kwargs: Parameters of freebsd-update command.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_update.py#L80-L123
[ "def _cmd(**kwargs):\n '''\n .. versionadded:: 2016.3.4\n\n Private function that returns the freebsd-update command string to be\n executed. It checks if any arguments are given to freebsd-update and appends\n them accordingly.\n '''\n update_cmd = salt.utils.path.which('freebsd-update')\n if not update_cmd:\n raise CommandNotFoundError('\"freebsd-update\" command not found')\n\n params = []\n if 'basedir' in kwargs:\n params.append('-b {0}'.format(kwargs['basedir']))\n if 'workdir' in kwargs:\n params.append('-d {0}'.format(kwargs['workdir']))\n if 'conffile' in kwargs:\n params.append('-f {0}'.format(kwargs['conffile']))\n if 'force' in kwargs:\n params.append('-F')\n if 'key' in kwargs:\n params.append('-k {0}'.format(kwargs['key']))\n if 'newrelease' in kwargs:\n params.append('-r {0}'.format(kwargs['newrelease']))\n if 'server' in kwargs:\n params.append('-s {0}'.format(kwargs['server']))\n if 'address' in kwargs:\n params.append('-t {0}'.format(kwargs['address']))\n\n if params:\n return '{0} {1}'.format(update_cmd, ' '.join(params))\n return update_cmd\n" ]
# -*- coding: utf-8 -*- ''' Support for freebsd-update utility on FreeBSD. .. versionadded:: 2017.7.0 :maintainer: George Mamalakis <mamalos@gmail.com> :maturity: new :platform: FreeBSD ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging # Import salt libs import salt.utils.path from salt.ext import six from salt.exceptions import CommandNotFoundError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'freebsd_update' __virtual_aliases__ = ('freebsd-update',) def __virtual__(): ''' .. versionadded:: 2016.3.4 Only work on FreeBSD RELEASEs >= 6.2, where freebsd-update was introduced. ''' if __grains__['os'] != 'FreeBSD': return (False, 'The freebsd_update execution module cannot be loaded: only available on FreeBSD systems.') if float(__grains__['osrelease']) < 6.2: return (False, 'freebsd_update is only available on FreeBSD versions >= 6.2-RELESE') if 'release' not in __grains__['kernelrelease'].lower(): return (False, 'freebsd_update is only available on FreeBSD RELEASES') return __virtualname__ def _cmd(**kwargs): ''' .. versionadded:: 2016.3.4 Private function that returns the freebsd-update command string to be executed. It checks if any arguments are given to freebsd-update and appends them accordingly. ''' update_cmd = salt.utils.path.which('freebsd-update') if not update_cmd: raise CommandNotFoundError('"freebsd-update" command not found') params = [] if 'basedir' in kwargs: params.append('-b {0}'.format(kwargs['basedir'])) if 'workdir' in kwargs: params.append('-d {0}'.format(kwargs['workdir'])) if 'conffile' in kwargs: params.append('-f {0}'.format(kwargs['conffile'])) if 'force' in kwargs: params.append('-F') if 'key' in kwargs: params.append('-k {0}'.format(kwargs['key'])) if 'newrelease' in kwargs: params.append('-r {0}'.format(kwargs['newrelease'])) if 'server' in kwargs: params.append('-s {0}'.format(kwargs['server'])) if 'address' in kwargs: params.append('-t {0}'.format(kwargs['address'])) if params: return '{0} {1}'.format(update_cmd, ' '.join(params)) return update_cmd def fetch(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update fetch wrapper. Based on the currently installed world and the configuration options set, fetch all available binary updates. kwargs: Parameters of freebsd-update command. ''' # fetch continues when no controlling terminal is present pre = '' post = '' run_args = {} if float(__grains__['osrelease']) >= 10.2: post += '--not-running-from-cron' else: pre += ' env PAGER=cat' run_args['python_shell'] = True return _wrapper('fetch', pre=pre, post=post, run_args=run_args, **kwargs) def install(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update install wrapper. Install the most recently fetched updates or upgrade. kwargs: Parameters of freebsd-update command. ''' return _wrapper('install', **kwargs) def rollback(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update rollback wrapper. Uninstalls the most recently installed updates. kwargs: Parameters of freebsd-update command. ''' return _wrapper('rollback', **kwargs) def update(**kwargs): ''' .. versionadded:: 2016.3.4 Command that simplifies freebsd-update by running freebsd-update fetch first and then freebsd-update install. kwargs: Parameters of freebsd-update command. ''' stdout = {} for mode in ('fetch', 'install'): err_ = {} ret = _wrapper(mode, err_=err_, **kwargs) if 'retcode' in err_ and err_['retcode'] != 0: return ret if 'stdout' in err_: stdout[mode] = err_['stdout'] return '\n'.join(['{0}: {1}'.format(k, v) for (k, v) in six.iteritems(stdout)]) def ids(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update IDS wrapper function. Compares the system against a "known good" index of the installed release. kwargs: Parameters of freebsd-update command. ''' return _wrapper('IDS', **kwargs) def upgrade(**kwargs): ''' .. versionadded:: 2016.3.4 Dummy function used only to print a message that upgrade is not available. The reason is that upgrade needs manual intervention and reboot, so even if used with: yes | freebsd-upgrade -r VERSION the additional freebsd-update install that needs to run after the reboot cannot be implemented easily. kwargs: Parameters of freebsd-update command. ''' msg = 'freebsd-update upgrade not yet implemented.' log.warning(msg) return msg
saltstack/salt
salt/modules/freebsd_update.py
fetch
python
def fetch(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update fetch wrapper. Based on the currently installed world and the configuration options set, fetch all available binary updates. kwargs: Parameters of freebsd-update command. ''' # fetch continues when no controlling terminal is present pre = '' post = '' run_args = {} if float(__grains__['osrelease']) >= 10.2: post += '--not-running-from-cron' else: pre += ' env PAGER=cat' run_args['python_shell'] = True return _wrapper('fetch', pre=pre, post=post, run_args=run_args, **kwargs)
.. versionadded:: 2016.3.4 freebsd-update fetch wrapper. Based on the currently installed world and the configuration options set, fetch all available binary updates. kwargs: Parameters of freebsd-update command.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_update.py#L126-L145
[ "def _wrapper(orig, pre='', post='', err_=None, run_args=None, **kwargs):\n '''\n Helper function that wraps the execution of freebsd-update command.\n\n orig:\n Originating function that called _wrapper().\n\n pre:\n String that will be prepended to freebsd-update command.\n\n post:\n String that will be appended to freebsd-update command.\n\n err_:\n Dictionary on which return codes and stout/stderr are copied.\n\n run_args:\n Arguments to be passed on cmd.run_all.\n\n kwargs:\n Parameters of freebsd-update command.\n '''\n ret = '' # the message to be returned\n cmd = _cmd(**kwargs)\n cmd_str = ' '.join([x for x in (pre, cmd, post, orig)])\n if run_args and isinstance(run_args, dict):\n res = __salt__['cmd.run_all'](cmd_str, **run_args)\n else:\n res = __salt__['cmd.run_all'](cmd_str)\n\n if isinstance(err_, dict): # copy return values if asked to\n for k, v in six.itermitems(res):\n err_[k] = v\n\n if 'retcode' in res and res['retcode'] != 0:\n msg = ' '.join([x for x in (res['stdout'], res['stderr']) if x])\n ret = 'Unable to run \"{0}\" with run_args=\"{1}\". Error: {2}'.format(cmd_str, run_args, msg)\n log.error(ret)\n else:\n try:\n ret = res['stdout']\n except KeyError:\n log.error(\"cmd.run_all did not return a dictionary with a key named 'stdout'\")\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for freebsd-update utility on FreeBSD. .. versionadded:: 2017.7.0 :maintainer: George Mamalakis <mamalos@gmail.com> :maturity: new :platform: FreeBSD ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging # Import salt libs import salt.utils.path from salt.ext import six from salt.exceptions import CommandNotFoundError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'freebsd_update' __virtual_aliases__ = ('freebsd-update',) def __virtual__(): ''' .. versionadded:: 2016.3.4 Only work on FreeBSD RELEASEs >= 6.2, where freebsd-update was introduced. ''' if __grains__['os'] != 'FreeBSD': return (False, 'The freebsd_update execution module cannot be loaded: only available on FreeBSD systems.') if float(__grains__['osrelease']) < 6.2: return (False, 'freebsd_update is only available on FreeBSD versions >= 6.2-RELESE') if 'release' not in __grains__['kernelrelease'].lower(): return (False, 'freebsd_update is only available on FreeBSD RELEASES') return __virtualname__ def _cmd(**kwargs): ''' .. versionadded:: 2016.3.4 Private function that returns the freebsd-update command string to be executed. It checks if any arguments are given to freebsd-update and appends them accordingly. ''' update_cmd = salt.utils.path.which('freebsd-update') if not update_cmd: raise CommandNotFoundError('"freebsd-update" command not found') params = [] if 'basedir' in kwargs: params.append('-b {0}'.format(kwargs['basedir'])) if 'workdir' in kwargs: params.append('-d {0}'.format(kwargs['workdir'])) if 'conffile' in kwargs: params.append('-f {0}'.format(kwargs['conffile'])) if 'force' in kwargs: params.append('-F') if 'key' in kwargs: params.append('-k {0}'.format(kwargs['key'])) if 'newrelease' in kwargs: params.append('-r {0}'.format(kwargs['newrelease'])) if 'server' in kwargs: params.append('-s {0}'.format(kwargs['server'])) if 'address' in kwargs: params.append('-t {0}'.format(kwargs['address'])) if params: return '{0} {1}'.format(update_cmd, ' '.join(params)) return update_cmd def _wrapper(orig, pre='', post='', err_=None, run_args=None, **kwargs): ''' Helper function that wraps the execution of freebsd-update command. orig: Originating function that called _wrapper(). pre: String that will be prepended to freebsd-update command. post: String that will be appended to freebsd-update command. err_: Dictionary on which return codes and stout/stderr are copied. run_args: Arguments to be passed on cmd.run_all. kwargs: Parameters of freebsd-update command. ''' ret = '' # the message to be returned cmd = _cmd(**kwargs) cmd_str = ' '.join([x for x in (pre, cmd, post, orig)]) if run_args and isinstance(run_args, dict): res = __salt__['cmd.run_all'](cmd_str, **run_args) else: res = __salt__['cmd.run_all'](cmd_str) if isinstance(err_, dict): # copy return values if asked to for k, v in six.itermitems(res): err_[k] = v if 'retcode' in res and res['retcode'] != 0: msg = ' '.join([x for x in (res['stdout'], res['stderr']) if x]) ret = 'Unable to run "{0}" with run_args="{1}". Error: {2}'.format(cmd_str, run_args, msg) log.error(ret) else: try: ret = res['stdout'] except KeyError: log.error("cmd.run_all did not return a dictionary with a key named 'stdout'") return ret def install(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update install wrapper. Install the most recently fetched updates or upgrade. kwargs: Parameters of freebsd-update command. ''' return _wrapper('install', **kwargs) def rollback(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update rollback wrapper. Uninstalls the most recently installed updates. kwargs: Parameters of freebsd-update command. ''' return _wrapper('rollback', **kwargs) def update(**kwargs): ''' .. versionadded:: 2016.3.4 Command that simplifies freebsd-update by running freebsd-update fetch first and then freebsd-update install. kwargs: Parameters of freebsd-update command. ''' stdout = {} for mode in ('fetch', 'install'): err_ = {} ret = _wrapper(mode, err_=err_, **kwargs) if 'retcode' in err_ and err_['retcode'] != 0: return ret if 'stdout' in err_: stdout[mode] = err_['stdout'] return '\n'.join(['{0}: {1}'.format(k, v) for (k, v) in six.iteritems(stdout)]) def ids(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update IDS wrapper function. Compares the system against a "known good" index of the installed release. kwargs: Parameters of freebsd-update command. ''' return _wrapper('IDS', **kwargs) def upgrade(**kwargs): ''' .. versionadded:: 2016.3.4 Dummy function used only to print a message that upgrade is not available. The reason is that upgrade needs manual intervention and reboot, so even if used with: yes | freebsd-upgrade -r VERSION the additional freebsd-update install that needs to run after the reboot cannot be implemented easily. kwargs: Parameters of freebsd-update command. ''' msg = 'freebsd-update upgrade not yet implemented.' log.warning(msg) return msg
saltstack/salt
salt/modules/freebsd_update.py
update
python
def update(**kwargs): ''' .. versionadded:: 2016.3.4 Command that simplifies freebsd-update by running freebsd-update fetch first and then freebsd-update install. kwargs: Parameters of freebsd-update command. ''' stdout = {} for mode in ('fetch', 'install'): err_ = {} ret = _wrapper(mode, err_=err_, **kwargs) if 'retcode' in err_ and err_['retcode'] != 0: return ret if 'stdout' in err_: stdout[mode] = err_['stdout'] return '\n'.join(['{0}: {1}'.format(k, v) for (k, v) in six.iteritems(stdout)])
.. versionadded:: 2016.3.4 Command that simplifies freebsd-update by running freebsd-update fetch first and then freebsd-update install. kwargs: Parameters of freebsd-update command.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_update.py#L174-L193
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _wrapper(orig, pre='', post='', err_=None, run_args=None, **kwargs):\n '''\n Helper function that wraps the execution of freebsd-update command.\n\n orig:\n Originating function that called _wrapper().\n\n pre:\n String that will be prepended to freebsd-update command.\n\n post:\n String that will be appended to freebsd-update command.\n\n err_:\n Dictionary on which return codes and stout/stderr are copied.\n\n run_args:\n Arguments to be passed on cmd.run_all.\n\n kwargs:\n Parameters of freebsd-update command.\n '''\n ret = '' # the message to be returned\n cmd = _cmd(**kwargs)\n cmd_str = ' '.join([x for x in (pre, cmd, post, orig)])\n if run_args and isinstance(run_args, dict):\n res = __salt__['cmd.run_all'](cmd_str, **run_args)\n else:\n res = __salt__['cmd.run_all'](cmd_str)\n\n if isinstance(err_, dict): # copy return values if asked to\n for k, v in six.itermitems(res):\n err_[k] = v\n\n if 'retcode' in res and res['retcode'] != 0:\n msg = ' '.join([x for x in (res['stdout'], res['stderr']) if x])\n ret = 'Unable to run \"{0}\" with run_args=\"{1}\". Error: {2}'.format(cmd_str, run_args, msg)\n log.error(ret)\n else:\n try:\n ret = res['stdout']\n except KeyError:\n log.error(\"cmd.run_all did not return a dictionary with a key named 'stdout'\")\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for freebsd-update utility on FreeBSD. .. versionadded:: 2017.7.0 :maintainer: George Mamalakis <mamalos@gmail.com> :maturity: new :platform: FreeBSD ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging # Import salt libs import salt.utils.path from salt.ext import six from salt.exceptions import CommandNotFoundError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'freebsd_update' __virtual_aliases__ = ('freebsd-update',) def __virtual__(): ''' .. versionadded:: 2016.3.4 Only work on FreeBSD RELEASEs >= 6.2, where freebsd-update was introduced. ''' if __grains__['os'] != 'FreeBSD': return (False, 'The freebsd_update execution module cannot be loaded: only available on FreeBSD systems.') if float(__grains__['osrelease']) < 6.2: return (False, 'freebsd_update is only available on FreeBSD versions >= 6.2-RELESE') if 'release' not in __grains__['kernelrelease'].lower(): return (False, 'freebsd_update is only available on FreeBSD RELEASES') return __virtualname__ def _cmd(**kwargs): ''' .. versionadded:: 2016.3.4 Private function that returns the freebsd-update command string to be executed. It checks if any arguments are given to freebsd-update and appends them accordingly. ''' update_cmd = salt.utils.path.which('freebsd-update') if not update_cmd: raise CommandNotFoundError('"freebsd-update" command not found') params = [] if 'basedir' in kwargs: params.append('-b {0}'.format(kwargs['basedir'])) if 'workdir' in kwargs: params.append('-d {0}'.format(kwargs['workdir'])) if 'conffile' in kwargs: params.append('-f {0}'.format(kwargs['conffile'])) if 'force' in kwargs: params.append('-F') if 'key' in kwargs: params.append('-k {0}'.format(kwargs['key'])) if 'newrelease' in kwargs: params.append('-r {0}'.format(kwargs['newrelease'])) if 'server' in kwargs: params.append('-s {0}'.format(kwargs['server'])) if 'address' in kwargs: params.append('-t {0}'.format(kwargs['address'])) if params: return '{0} {1}'.format(update_cmd, ' '.join(params)) return update_cmd def _wrapper(orig, pre='', post='', err_=None, run_args=None, **kwargs): ''' Helper function that wraps the execution of freebsd-update command. orig: Originating function that called _wrapper(). pre: String that will be prepended to freebsd-update command. post: String that will be appended to freebsd-update command. err_: Dictionary on which return codes and stout/stderr are copied. run_args: Arguments to be passed on cmd.run_all. kwargs: Parameters of freebsd-update command. ''' ret = '' # the message to be returned cmd = _cmd(**kwargs) cmd_str = ' '.join([x for x in (pre, cmd, post, orig)]) if run_args and isinstance(run_args, dict): res = __salt__['cmd.run_all'](cmd_str, **run_args) else: res = __salt__['cmd.run_all'](cmd_str) if isinstance(err_, dict): # copy return values if asked to for k, v in six.itermitems(res): err_[k] = v if 'retcode' in res and res['retcode'] != 0: msg = ' '.join([x for x in (res['stdout'], res['stderr']) if x]) ret = 'Unable to run "{0}" with run_args="{1}". Error: {2}'.format(cmd_str, run_args, msg) log.error(ret) else: try: ret = res['stdout'] except KeyError: log.error("cmd.run_all did not return a dictionary with a key named 'stdout'") return ret def fetch(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update fetch wrapper. Based on the currently installed world and the configuration options set, fetch all available binary updates. kwargs: Parameters of freebsd-update command. ''' # fetch continues when no controlling terminal is present pre = '' post = '' run_args = {} if float(__grains__['osrelease']) >= 10.2: post += '--not-running-from-cron' else: pre += ' env PAGER=cat' run_args['python_shell'] = True return _wrapper('fetch', pre=pre, post=post, run_args=run_args, **kwargs) def install(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update install wrapper. Install the most recently fetched updates or upgrade. kwargs: Parameters of freebsd-update command. ''' return _wrapper('install', **kwargs) def rollback(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update rollback wrapper. Uninstalls the most recently installed updates. kwargs: Parameters of freebsd-update command. ''' return _wrapper('rollback', **kwargs) def ids(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update IDS wrapper function. Compares the system against a "known good" index of the installed release. kwargs: Parameters of freebsd-update command. ''' return _wrapper('IDS', **kwargs) def upgrade(**kwargs): ''' .. versionadded:: 2016.3.4 Dummy function used only to print a message that upgrade is not available. The reason is that upgrade needs manual intervention and reboot, so even if used with: yes | freebsd-upgrade -r VERSION the additional freebsd-update install that needs to run after the reboot cannot be implemented easily. kwargs: Parameters of freebsd-update command. ''' msg = 'freebsd-update upgrade not yet implemented.' log.warning(msg) return msg
saltstack/salt
salt/states/flatpak.py
uninstalled
python
def uninstalled(name): ''' Ensure that the named package is not installed. Args: name (str): The flatpak package. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml uninstall_package: flatpack.uninstalled: - name: gimp ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} old = __salt__['flatpak.is_installed'](name) if not old: ret['comment'] = 'Package {0} is not installed'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = 'Package {0} would have been uninstalled'.format(name) ret['changes']['old'] = old[0]['version'] ret['changes']['new'] = None ret['result'] = None return ret __salt__['flatpak.uninstall'](name) if not __salt__['flatpak.is_installed'](name): ret['comment'] = 'Package {0} uninstalled'.format(name) ret['changes']['old'] = old[0]['version'] ret['changes']['new'] = None ret['result'] = True return ret
Ensure that the named package is not installed. Args: name (str): The flatpak package. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml uninstall_package: flatpack.uninstalled: - name: gimp
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/flatpak.py#L79-L121
null
# -*- coding: utf-8 -*- ''' Management of flatpak packages ============================== Allows the installation and uninstallation of flatpak packages. .. versionadded:: Neon ''' from __future__ import absolute_import, print_function, unicode_literals import salt.utils.path __virtualname__ = 'flatpak' def __virtual__(): if salt.utils.path.which('flatpak'): return __virtualname__ return False, 'The flatpak state module cannot be loaded: the "flatpak" binary is not in the path.' def installed(location, name): ''' Ensure that the named package is installed. Args: location (str): The location or remote to install the flatpak from. name (str): The name of the package or runtime. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml install_package: flatpack.installed: - location: flathub - name: gimp ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} old = __salt__['flatpak.is_installed'](name) if not old: if __opts__['test']: ret['comment'] = 'Package "{0}" would have been installed'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = None return ret install_ret = __salt__['flatpak.install'](name, location) if __salt__['flatpak.is_installed'](name): ret['comment'] = 'Package "{0}" was installed'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = True return ret ret['comment'] = 'Package "{0}" failed to install'.format(name) ret['comment'] += '\noutput:\n' + install_ret['output'] ret['result'] = False return ret ret['comment'] = 'Package "{0}" is already installed'.format(name) if __opts__['test']: ret['result'] = None return ret ret['result'] = True return ret def add_remote(name, location): ''' Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml add_flathub: flatpack.add_remote: - name: flathub - location: https://flathub.org/repo/flathub.flatpakrepo ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} old = __salt__['flatpak.is_remote_added'](name) if not old: if __opts__['test']: ret['comment'] = 'Remote "{0}" would have been added'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = None return ret install_ret = __salt__['flatpak.add_remote'](name) if __salt__['flatpak.is_remote_added'](name): ret['comment'] = 'Remote "{0}" was added'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = True return ret ret['comment'] = 'Failed to add remote "{0}"'.format(name) ret['comment'] += '\noutput:\n' + install_ret['output'] ret['result'] = False return ret ret['comment'] = 'Remote "{0}" already exists'.format(name) if __opts__['test']: ret['result'] = None return ret ret['result'] = True return ret
saltstack/salt
salt/states/flatpak.py
add_remote
python
def add_remote(name, location): ''' Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml add_flathub: flatpack.add_remote: - name: flathub - location: https://flathub.org/repo/flathub.flatpakrepo ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} old = __salt__['flatpak.is_remote_added'](name) if not old: if __opts__['test']: ret['comment'] = 'Remote "{0}" would have been added'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = None return ret install_ret = __salt__['flatpak.add_remote'](name) if __salt__['flatpak.is_remote_added'](name): ret['comment'] = 'Remote "{0}" was added'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = True return ret ret['comment'] = 'Failed to add remote "{0}"'.format(name) ret['comment'] += '\noutput:\n' + install_ret['output'] ret['result'] = False return ret ret['comment'] = 'Remote "{0}" already exists'.format(name) if __opts__['test']: ret['result'] = None return ret ret['result'] = True return ret
Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml add_flathub: flatpack.add_remote: - name: flathub - location: https://flathub.org/repo/flathub.flatpakrepo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/flatpak.py#L124-L177
null
# -*- coding: utf-8 -*- ''' Management of flatpak packages ============================== Allows the installation and uninstallation of flatpak packages. .. versionadded:: Neon ''' from __future__ import absolute_import, print_function, unicode_literals import salt.utils.path __virtualname__ = 'flatpak' def __virtual__(): if salt.utils.path.which('flatpak'): return __virtualname__ return False, 'The flatpak state module cannot be loaded: the "flatpak" binary is not in the path.' def installed(location, name): ''' Ensure that the named package is installed. Args: location (str): The location or remote to install the flatpak from. name (str): The name of the package or runtime. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml install_package: flatpack.installed: - location: flathub - name: gimp ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} old = __salt__['flatpak.is_installed'](name) if not old: if __opts__['test']: ret['comment'] = 'Package "{0}" would have been installed'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = None return ret install_ret = __salt__['flatpak.install'](name, location) if __salt__['flatpak.is_installed'](name): ret['comment'] = 'Package "{0}" was installed'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = True return ret ret['comment'] = 'Package "{0}" failed to install'.format(name) ret['comment'] += '\noutput:\n' + install_ret['output'] ret['result'] = False return ret ret['comment'] = 'Package "{0}" is already installed'.format(name) if __opts__['test']: ret['result'] = None return ret ret['result'] = True return ret def uninstalled(name): ''' Ensure that the named package is not installed. Args: name (str): The flatpak package. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml uninstall_package: flatpack.uninstalled: - name: gimp ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} old = __salt__['flatpak.is_installed'](name) if not old: ret['comment'] = 'Package {0} is not installed'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = 'Package {0} would have been uninstalled'.format(name) ret['changes']['old'] = old[0]['version'] ret['changes']['new'] = None ret['result'] = None return ret __salt__['flatpak.uninstall'](name) if not __salt__['flatpak.is_installed'](name): ret['comment'] = 'Package {0} uninstalled'.format(name) ret['changes']['old'] = old[0]['version'] ret['changes']['new'] = None ret['result'] = True return ret
saltstack/salt
salt/modules/smartos_nictagadm.py
list_nictags
python
def list_nictags(include_etherstubs=True): ''' List all nictags include_etherstubs : boolean toggle include of etherstubs CLI Example: .. code-block:: bash salt '*' nictagadm.list ''' ret = {} cmd = 'nictagadm list -d "|" -p{0}'.format( ' -L' if not include_etherstubs else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.' else: header = ['name', 'macaddress', 'link', 'type'] for nictag in res['stdout'].splitlines(): nictag = nictag.split('|') nictag_data = {} for field in header: nictag_data[field] = nictag[header.index(field)] ret[nictag_data['name']] = nictag_data del ret[nictag_data['name']]['name'] return ret
List all nictags include_etherstubs : boolean toggle include of etherstubs CLI Example: .. code-block:: bash salt '*' nictagadm.list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L48-L78
null
# -*- coding: utf-8 -*- ''' Module for running nictagadm command on SmartOS :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: nictagadm binary, dladm binary :platform: smartos ..versionadded:: 2016.11.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import Salt libs import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) # Function aliases __func_alias__ = { 'list_nictags': 'list' } # Define the module's virtual name __virtualname__ = 'nictagadm' def __virtual__(): ''' Provides nictagadm on SmartOS ''' if salt.utils.platform.is_smartos_globalzone() and \ salt.utils.path.which('dladm') and \ salt.utils.path.which('nictagadm'): return __virtualname__ return ( False, '{0} module can only be loaded on SmartOS compute nodes'.format( __virtualname__ ) ) def vms(nictag): ''' List all vms connect to nictag nictag : string name of nictag CLI Example: .. code-block:: bash salt '*' nictagadm.vms admin ''' ret = {} cmd = 'nictagadm vms {0}'.format(nictag) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.' else: ret = res['stdout'].splitlines() return ret def exists(*nictag, **kwargs): ''' Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if not nictag: return {'Error': 'Please provide at least one nictag to check.'} cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag)) res = __salt__['cmd.run_all'](cmd) if not kwargs.get('verbose', False): ret = res['retcode'] == 0 else: missing = res['stderr'].splitlines() for nt in nictag: ret[nt] = nt not in missing return ret def add(name, mac, mtu=1500): ''' Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add storage0 etherstub salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000 ''' ret = {} if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac != 'etherstub': cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac == 'etherstub': cmd = 'nictagadm add -l {0}'.format(name) res = __salt__['cmd.run_all'](cmd) else: cmd = 'nictagadm add -p mtu={0},mac={1} {2}'.format(mtu, mac, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to create nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def update(name, mac=None, mtu=None): ''' Update a nictag name : string name of nictag mac : string optional new mac for nictag mtu : int optional new MTU for nictag CLI Example: .. code-block:: bash salt '*' nictagadm.update trunk mtu=9000 ''' ret = {} if name not in list_nictags(): return {'Error': 'nictag {0} does not exists.'.format(name)} if not mtu and not mac: return {'Error': 'please provide either mac or/and mtu.'} if mtu: if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac: if mac == 'etherstub': return {'Error': 'cannot update a nic with "etherstub".'} else: cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac and mtu: properties = "mtu={0},mac={1}".format(mtu, mac) elif mac: properties = "mac={0}".format(mac) if mac else "" elif mtu: properties = "mtu={0}".format(mtu) if mtu else "" cmd = 'nictagadm update -p {0} {1}'.format(properties, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to update nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def delete(name, force=False): ''' Delete nictag name : string nictag to delete force : boolean force delete even if vms attached CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if name not in list_nictags(): return True cmd = 'nictagadm delete {0}{1}'.format("-f " if force else "", name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to delete nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/smartos_nictagadm.py
vms
python
def vms(nictag): ''' List all vms connect to nictag nictag : string name of nictag CLI Example: .. code-block:: bash salt '*' nictagadm.vms admin ''' ret = {} cmd = 'nictagadm vms {0}'.format(nictag) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.' else: ret = res['stdout'].splitlines() return ret
List all vms connect to nictag nictag : string name of nictag CLI Example: .. code-block:: bash salt '*' nictagadm.vms admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L81-L102
null
# -*- coding: utf-8 -*- ''' Module for running nictagadm command on SmartOS :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: nictagadm binary, dladm binary :platform: smartos ..versionadded:: 2016.11.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import Salt libs import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) # Function aliases __func_alias__ = { 'list_nictags': 'list' } # Define the module's virtual name __virtualname__ = 'nictagadm' def __virtual__(): ''' Provides nictagadm on SmartOS ''' if salt.utils.platform.is_smartos_globalzone() and \ salt.utils.path.which('dladm') and \ salt.utils.path.which('nictagadm'): return __virtualname__ return ( False, '{0} module can only be loaded on SmartOS compute nodes'.format( __virtualname__ ) ) def list_nictags(include_etherstubs=True): ''' List all nictags include_etherstubs : boolean toggle include of etherstubs CLI Example: .. code-block:: bash salt '*' nictagadm.list ''' ret = {} cmd = 'nictagadm list -d "|" -p{0}'.format( ' -L' if not include_etherstubs else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.' else: header = ['name', 'macaddress', 'link', 'type'] for nictag in res['stdout'].splitlines(): nictag = nictag.split('|') nictag_data = {} for field in header: nictag_data[field] = nictag[header.index(field)] ret[nictag_data['name']] = nictag_data del ret[nictag_data['name']]['name'] return ret def exists(*nictag, **kwargs): ''' Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if not nictag: return {'Error': 'Please provide at least one nictag to check.'} cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag)) res = __salt__['cmd.run_all'](cmd) if not kwargs.get('verbose', False): ret = res['retcode'] == 0 else: missing = res['stderr'].splitlines() for nt in nictag: ret[nt] = nt not in missing return ret def add(name, mac, mtu=1500): ''' Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add storage0 etherstub salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000 ''' ret = {} if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac != 'etherstub': cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac == 'etherstub': cmd = 'nictagadm add -l {0}'.format(name) res = __salt__['cmd.run_all'](cmd) else: cmd = 'nictagadm add -p mtu={0},mac={1} {2}'.format(mtu, mac, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to create nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def update(name, mac=None, mtu=None): ''' Update a nictag name : string name of nictag mac : string optional new mac for nictag mtu : int optional new MTU for nictag CLI Example: .. code-block:: bash salt '*' nictagadm.update trunk mtu=9000 ''' ret = {} if name not in list_nictags(): return {'Error': 'nictag {0} does not exists.'.format(name)} if not mtu and not mac: return {'Error': 'please provide either mac or/and mtu.'} if mtu: if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac: if mac == 'etherstub': return {'Error': 'cannot update a nic with "etherstub".'} else: cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac and mtu: properties = "mtu={0},mac={1}".format(mtu, mac) elif mac: properties = "mac={0}".format(mac) if mac else "" elif mtu: properties = "mtu={0}".format(mtu) if mtu else "" cmd = 'nictagadm update -p {0} {1}'.format(properties, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to update nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def delete(name, force=False): ''' Delete nictag name : string nictag to delete force : boolean force delete even if vms attached CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if name not in list_nictags(): return True cmd = 'nictagadm delete {0}{1}'.format("-f " if force else "", name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to delete nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/smartos_nictagadm.py
exists
python
def exists(*nictag, **kwargs): ''' Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if not nictag: return {'Error': 'Please provide at least one nictag to check.'} cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag)) res = __salt__['cmd.run_all'](cmd) if not kwargs.get('verbose', False): ret = res['retcode'] == 0 else: missing = res['stderr'].splitlines() for nt in nictag: ret[nt] = nt not in missing return ret
Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L105-L134
null
# -*- coding: utf-8 -*- ''' Module for running nictagadm command on SmartOS :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: nictagadm binary, dladm binary :platform: smartos ..versionadded:: 2016.11.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import Salt libs import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) # Function aliases __func_alias__ = { 'list_nictags': 'list' } # Define the module's virtual name __virtualname__ = 'nictagadm' def __virtual__(): ''' Provides nictagadm on SmartOS ''' if salt.utils.platform.is_smartos_globalzone() and \ salt.utils.path.which('dladm') and \ salt.utils.path.which('nictagadm'): return __virtualname__ return ( False, '{0} module can only be loaded on SmartOS compute nodes'.format( __virtualname__ ) ) def list_nictags(include_etherstubs=True): ''' List all nictags include_etherstubs : boolean toggle include of etherstubs CLI Example: .. code-block:: bash salt '*' nictagadm.list ''' ret = {} cmd = 'nictagadm list -d "|" -p{0}'.format( ' -L' if not include_etherstubs else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.' else: header = ['name', 'macaddress', 'link', 'type'] for nictag in res['stdout'].splitlines(): nictag = nictag.split('|') nictag_data = {} for field in header: nictag_data[field] = nictag[header.index(field)] ret[nictag_data['name']] = nictag_data del ret[nictag_data['name']]['name'] return ret def vms(nictag): ''' List all vms connect to nictag nictag : string name of nictag CLI Example: .. code-block:: bash salt '*' nictagadm.vms admin ''' ret = {} cmd = 'nictagadm vms {0}'.format(nictag) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.' else: ret = res['stdout'].splitlines() return ret def add(name, mac, mtu=1500): ''' Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add storage0 etherstub salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000 ''' ret = {} if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac != 'etherstub': cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac == 'etherstub': cmd = 'nictagadm add -l {0}'.format(name) res = __salt__['cmd.run_all'](cmd) else: cmd = 'nictagadm add -p mtu={0},mac={1} {2}'.format(mtu, mac, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to create nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def update(name, mac=None, mtu=None): ''' Update a nictag name : string name of nictag mac : string optional new mac for nictag mtu : int optional new MTU for nictag CLI Example: .. code-block:: bash salt '*' nictagadm.update trunk mtu=9000 ''' ret = {} if name not in list_nictags(): return {'Error': 'nictag {0} does not exists.'.format(name)} if not mtu and not mac: return {'Error': 'please provide either mac or/and mtu.'} if mtu: if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac: if mac == 'etherstub': return {'Error': 'cannot update a nic with "etherstub".'} else: cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac and mtu: properties = "mtu={0},mac={1}".format(mtu, mac) elif mac: properties = "mac={0}".format(mac) if mac else "" elif mtu: properties = "mtu={0}".format(mtu) if mtu else "" cmd = 'nictagadm update -p {0} {1}'.format(properties, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to update nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def delete(name, force=False): ''' Delete nictag name : string nictag to delete force : boolean force delete even if vms attached CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if name not in list_nictags(): return True cmd = 'nictagadm delete {0}{1}'.format("-f " if force else "", name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to delete nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/smartos_nictagadm.py
add
python
def add(name, mac, mtu=1500): ''' Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add storage0 etherstub salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000 ''' ret = {} if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac != 'etherstub': cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac == 'etherstub': cmd = 'nictagadm add -l {0}'.format(name) res = __salt__['cmd.run_all'](cmd) else: cmd = 'nictagadm add -p mtu={0},mac={1} {2}'.format(mtu, mac, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to create nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']}
Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add storage0 etherstub salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L137-L176
null
# -*- coding: utf-8 -*- ''' Module for running nictagadm command on SmartOS :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: nictagadm binary, dladm binary :platform: smartos ..versionadded:: 2016.11.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import Salt libs import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) # Function aliases __func_alias__ = { 'list_nictags': 'list' } # Define the module's virtual name __virtualname__ = 'nictagadm' def __virtual__(): ''' Provides nictagadm on SmartOS ''' if salt.utils.platform.is_smartos_globalzone() and \ salt.utils.path.which('dladm') and \ salt.utils.path.which('nictagadm'): return __virtualname__ return ( False, '{0} module can only be loaded on SmartOS compute nodes'.format( __virtualname__ ) ) def list_nictags(include_etherstubs=True): ''' List all nictags include_etherstubs : boolean toggle include of etherstubs CLI Example: .. code-block:: bash salt '*' nictagadm.list ''' ret = {} cmd = 'nictagadm list -d "|" -p{0}'.format( ' -L' if not include_etherstubs else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.' else: header = ['name', 'macaddress', 'link', 'type'] for nictag in res['stdout'].splitlines(): nictag = nictag.split('|') nictag_data = {} for field in header: nictag_data[field] = nictag[header.index(field)] ret[nictag_data['name']] = nictag_data del ret[nictag_data['name']]['name'] return ret def vms(nictag): ''' List all vms connect to nictag nictag : string name of nictag CLI Example: .. code-block:: bash salt '*' nictagadm.vms admin ''' ret = {} cmd = 'nictagadm vms {0}'.format(nictag) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.' else: ret = res['stdout'].splitlines() return ret def exists(*nictag, **kwargs): ''' Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if not nictag: return {'Error': 'Please provide at least one nictag to check.'} cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag)) res = __salt__['cmd.run_all'](cmd) if not kwargs.get('verbose', False): ret = res['retcode'] == 0 else: missing = res['stderr'].splitlines() for nt in nictag: ret[nt] = nt not in missing return ret def update(name, mac=None, mtu=None): ''' Update a nictag name : string name of nictag mac : string optional new mac for nictag mtu : int optional new MTU for nictag CLI Example: .. code-block:: bash salt '*' nictagadm.update trunk mtu=9000 ''' ret = {} if name not in list_nictags(): return {'Error': 'nictag {0} does not exists.'.format(name)} if not mtu and not mac: return {'Error': 'please provide either mac or/and mtu.'} if mtu: if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac: if mac == 'etherstub': return {'Error': 'cannot update a nic with "etherstub".'} else: cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac and mtu: properties = "mtu={0},mac={1}".format(mtu, mac) elif mac: properties = "mac={0}".format(mac) if mac else "" elif mtu: properties = "mtu={0}".format(mtu) if mtu else "" cmd = 'nictagadm update -p {0} {1}'.format(properties, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to update nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def delete(name, force=False): ''' Delete nictag name : string nictag to delete force : boolean force delete even if vms attached CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if name not in list_nictags(): return True cmd = 'nictagadm delete {0}{1}'.format("-f " if force else "", name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to delete nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/smartos_nictagadm.py
update
python
def update(name, mac=None, mtu=None): ''' Update a nictag name : string name of nictag mac : string optional new mac for nictag mtu : int optional new MTU for nictag CLI Example: .. code-block:: bash salt '*' nictagadm.update trunk mtu=9000 ''' ret = {} if name not in list_nictags(): return {'Error': 'nictag {0} does not exists.'.format(name)} if not mtu and not mac: return {'Error': 'please provide either mac or/and mtu.'} if mtu: if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac: if mac == 'etherstub': return {'Error': 'cannot update a nic with "etherstub".'} else: cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac and mtu: properties = "mtu={0},mac={1}".format(mtu, mac) elif mac: properties = "mac={0}".format(mac) if mac else "" elif mtu: properties = "mtu={0}".format(mtu) if mtu else "" cmd = 'nictagadm update -p {0} {1}'.format(properties, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to update nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']}
Update a nictag name : string name of nictag mac : string optional new mac for nictag mtu : int optional new MTU for nictag CLI Example: .. code-block:: bash salt '*' nictagadm.update trunk mtu=9000
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L179-L228
[ "def list_nictags(include_etherstubs=True):\n '''\n List all nictags\n\n include_etherstubs : boolean\n toggle include of etherstubs\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nictagadm.list\n '''\n ret = {}\n cmd = 'nictagadm list -d \"|\" -p{0}'.format(\n ' -L' if not include_etherstubs else ''\n )\n res = __salt__['cmd.run_all'](cmd)\n retcode = res['retcode']\n if retcode != 0:\n ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.'\n else:\n header = ['name', 'macaddress', 'link', 'type']\n for nictag in res['stdout'].splitlines():\n nictag = nictag.split('|')\n nictag_data = {}\n for field in header:\n nictag_data[field] = nictag[header.index(field)]\n ret[nictag_data['name']] = nictag_data\n del ret[nictag_data['name']]['name']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for running nictagadm command on SmartOS :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: nictagadm binary, dladm binary :platform: smartos ..versionadded:: 2016.11.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import Salt libs import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) # Function aliases __func_alias__ = { 'list_nictags': 'list' } # Define the module's virtual name __virtualname__ = 'nictagadm' def __virtual__(): ''' Provides nictagadm on SmartOS ''' if salt.utils.platform.is_smartos_globalzone() and \ salt.utils.path.which('dladm') and \ salt.utils.path.which('nictagadm'): return __virtualname__ return ( False, '{0} module can only be loaded on SmartOS compute nodes'.format( __virtualname__ ) ) def list_nictags(include_etherstubs=True): ''' List all nictags include_etherstubs : boolean toggle include of etherstubs CLI Example: .. code-block:: bash salt '*' nictagadm.list ''' ret = {} cmd = 'nictagadm list -d "|" -p{0}'.format( ' -L' if not include_etherstubs else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.' else: header = ['name', 'macaddress', 'link', 'type'] for nictag in res['stdout'].splitlines(): nictag = nictag.split('|') nictag_data = {} for field in header: nictag_data[field] = nictag[header.index(field)] ret[nictag_data['name']] = nictag_data del ret[nictag_data['name']]['name'] return ret def vms(nictag): ''' List all vms connect to nictag nictag : string name of nictag CLI Example: .. code-block:: bash salt '*' nictagadm.vms admin ''' ret = {} cmd = 'nictagadm vms {0}'.format(nictag) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.' else: ret = res['stdout'].splitlines() return ret def exists(*nictag, **kwargs): ''' Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if not nictag: return {'Error': 'Please provide at least one nictag to check.'} cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag)) res = __salt__['cmd.run_all'](cmd) if not kwargs.get('verbose', False): ret = res['retcode'] == 0 else: missing = res['stderr'].splitlines() for nt in nictag: ret[nt] = nt not in missing return ret def add(name, mac, mtu=1500): ''' Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add storage0 etherstub salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000 ''' ret = {} if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac != 'etherstub': cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac == 'etherstub': cmd = 'nictagadm add -l {0}'.format(name) res = __salt__['cmd.run_all'](cmd) else: cmd = 'nictagadm add -p mtu={0},mac={1} {2}'.format(mtu, mac, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to create nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def delete(name, force=False): ''' Delete nictag name : string nictag to delete force : boolean force delete even if vms attached CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if name not in list_nictags(): return True cmd = 'nictagadm delete {0}{1}'.format("-f " if force else "", name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to delete nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/smartos_nictagadm.py
delete
python
def delete(name, force=False): ''' Delete nictag name : string nictag to delete force : boolean force delete even if vms attached CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if name not in list_nictags(): return True cmd = 'nictagadm delete {0}{1}'.format("-f " if force else "", name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to delete nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']}
Delete nictag name : string nictag to delete force : boolean force delete even if vms attached CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L231-L257
[ "def list_nictags(include_etherstubs=True):\n '''\n List all nictags\n\n include_etherstubs : boolean\n toggle include of etherstubs\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nictagadm.list\n '''\n ret = {}\n cmd = 'nictagadm list -d \"|\" -p{0}'.format(\n ' -L' if not include_etherstubs else ''\n )\n res = __salt__['cmd.run_all'](cmd)\n retcode = res['retcode']\n if retcode != 0:\n ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.'\n else:\n header = ['name', 'macaddress', 'link', 'type']\n for nictag in res['stdout'].splitlines():\n nictag = nictag.split('|')\n nictag_data = {}\n for field in header:\n nictag_data[field] = nictag[header.index(field)]\n ret[nictag_data['name']] = nictag_data\n del ret[nictag_data['name']]['name']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for running nictagadm command on SmartOS :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: nictagadm binary, dladm binary :platform: smartos ..versionadded:: 2016.11.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import Salt libs import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) # Function aliases __func_alias__ = { 'list_nictags': 'list' } # Define the module's virtual name __virtualname__ = 'nictagadm' def __virtual__(): ''' Provides nictagadm on SmartOS ''' if salt.utils.platform.is_smartos_globalzone() and \ salt.utils.path.which('dladm') and \ salt.utils.path.which('nictagadm'): return __virtualname__ return ( False, '{0} module can only be loaded on SmartOS compute nodes'.format( __virtualname__ ) ) def list_nictags(include_etherstubs=True): ''' List all nictags include_etherstubs : boolean toggle include of etherstubs CLI Example: .. code-block:: bash salt '*' nictagadm.list ''' ret = {} cmd = 'nictagadm list -d "|" -p{0}'.format( ' -L' if not include_etherstubs else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.' else: header = ['name', 'macaddress', 'link', 'type'] for nictag in res['stdout'].splitlines(): nictag = nictag.split('|') nictag_data = {} for field in header: nictag_data[field] = nictag[header.index(field)] ret[nictag_data['name']] = nictag_data del ret[nictag_data['name']]['name'] return ret def vms(nictag): ''' List all vms connect to nictag nictag : string name of nictag CLI Example: .. code-block:: bash salt '*' nictagadm.vms admin ''' ret = {} cmd = 'nictagadm vms {0}'.format(nictag) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.' else: ret = res['stdout'].splitlines() return ret def exists(*nictag, **kwargs): ''' Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if not nictag: return {'Error': 'Please provide at least one nictag to check.'} cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag)) res = __salt__['cmd.run_all'](cmd) if not kwargs.get('verbose', False): ret = res['retcode'] == 0 else: missing = res['stderr'].splitlines() for nt in nictag: ret[nt] = nt not in missing return ret def add(name, mac, mtu=1500): ''' Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add storage0 etherstub salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000 ''' ret = {} if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac != 'etherstub': cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac == 'etherstub': cmd = 'nictagadm add -l {0}'.format(name) res = __salt__['cmd.run_all'](cmd) else: cmd = 'nictagadm add -p mtu={0},mac={1} {2}'.format(mtu, mac, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to create nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} def update(name, mac=None, mtu=None): ''' Update a nictag name : string name of nictag mac : string optional new mac for nictag mtu : int optional new MTU for nictag CLI Example: .. code-block:: bash salt '*' nictagadm.update trunk mtu=9000 ''' ret = {} if name not in list_nictags(): return {'Error': 'nictag {0} does not exists.'.format(name)} if not mtu and not mac: return {'Error': 'please provide either mac or/and mtu.'} if mtu: if mtu > 9000 or mtu < 1500: return {'Error': 'mtu must be a value between 1500 and 9000.'} if mac: if mac == 'etherstub': return {'Error': 'cannot update a nic with "etherstub".'} else: cmd = 'dladm show-phys -m -p -o address' res = __salt__['cmd.run_all'](cmd) # dladm prints '00' as '0', so account for that. if mac.replace('00', '0') not in res['stdout'].splitlines(): return {'Error': '{0} is not present on this system.'.format(mac)} if mac and mtu: properties = "mtu={0},mac={1}".format(mtu, mac) elif mac: properties = "mac={0}".format(mac) if mac else "" elif mtu: properties = "mtu={0}".format(mtu) if mtu else "" cmd = 'nictagadm update -p {0} {1}'.format(properties, name) res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: return True else: return {'Error': 'failed to update nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/proxy/philips_hue.py
init
python
def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user'])
Initialize the module.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L79-L91
null
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
_query
python
def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res
Query the URI :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L110-L137
[ "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 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
_set
python
def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res
Set state to the device by ID. :param lamp_id: :param state: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L140-L161
[ "def _query(lamp_id, state, action='', method='GET'):\n '''\n Query the URI\n\n :return:\n '''\n # Because salt.utils.query is that dreadful... :(\n\n err = None\n url = \"{0}/lights{1}\".format(CONFIG['uri'],\n lamp_id and '/{0}'.format(lamp_id) or '') \\\n + (action and \"/{0}\".format(action) or '')\n conn = http_client.HTTPConnection(CONFIG['host'])\n if method == 'PUT':\n conn.request(method, url, salt.utils.json.dumps(state))\n else:\n conn.request(method, url)\n resp = conn.getresponse()\n\n if resp.status == http_client.OK:\n res = salt.utils.json.loads(resp.read())\n else:\n err = \"HTTP error: {0}, {1}\".format(resp.status, resp.reason)\n conn.close()\n if err:\n raise CommandExecutionError(err)\n\n return res\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
_get_devices
python
def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")]
Parse device(s) ID(s) from the common params. :param params: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L164-L175
null
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
call_lights
python
def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False
Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L186-L208
[ "def _get_devices(params):\n '''\n Parse device(s) ID(s) from the common params.\n\n :param params:\n :return:\n '''\n if 'id' not in params:\n raise CommandExecutionError(\"Parameter ID is required.\")\n\n return type(params['id']) == int and [params['id']] \\\n or [int(dev) for dev in params['id'].split(\",\")]\n", "def _get_lights():\n '''\n Get all available lighting devices.\n '''\n return _query(None, None)\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
call_switch
python
def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out
Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L211-L241
[ "def _set(lamp_id, state, method=\"state\"):\n '''\n Set state to the device by ID.\n\n :param lamp_id:\n :param state:\n :return:\n '''\n try:\n res = _query(lamp_id, state, action=method, method='PUT')\n except Exception as err:\n raise CommandExecutionError(err)\n\n res = len(res) > 1 and res[-1] or res[0]\n if res.get('success'):\n res = {'result': True}\n elif res.get('error'):\n res = {'result': False,\n 'description': res['error']['description'],\n 'type': res['error']['type']}\n\n return res\n", "def _get_devices(params):\n '''\n Parse device(s) ID(s) from the common params.\n\n :param params:\n :return:\n '''\n if 'id' not in params:\n raise CommandExecutionError(\"Parameter ID is required.\")\n\n return type(params['id']) == int and [params['id']] \\\n or [int(dev) for dev in params['id'].split(\",\")]\n", "def _get_lights():\n '''\n Get all available lighting devices.\n '''\n return _query(None, None)\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
call_blink
python
def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res
Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L244-L270
[ "def _set(lamp_id, state, method=\"state\"):\n '''\n Set state to the device by ID.\n\n :param lamp_id:\n :param state:\n :return:\n '''\n try:\n res = _query(lamp_id, state, action=method, method='PUT')\n except Exception as err:\n raise CommandExecutionError(err)\n\n res = len(res) > 1 and res[-1] or res[0]\n if res.get('success'):\n res = {'result': True}\n elif res.get('error'):\n res = {'result': False,\n 'description': res['error']['description'],\n 'type': res['error']['type']}\n\n return res\n", "def _get_devices(params):\n '''\n Parse device(s) ID(s) from the common params.\n\n :param params:\n :return:\n '''\n if 'id' not in params:\n raise CommandExecutionError(\"Parameter ID is required.\")\n\n return type(params['id']) == int and [params['id']] \\\n or [int(dev) for dev in params['id'].split(\",\")]\n", "def _get_lights():\n '''\n Get all available lighting devices.\n '''\n return _query(None, None)\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
call_ping
python
def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True
Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L273-L288
[ "def call_blink(*args, **kwargs):\n '''\n Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF.\n\n Options:\n\n * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.\n * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' hue.blink id=1\n salt '*' hue.blink id=1,2,3\n '''\n devices = _get_lights()\n pause = kwargs.get('pause', 0)\n res = dict()\n for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):\n state = devices[six.text_type(dev_id)]['state']['on']\n _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON)\n if pause:\n time.sleep(pause)\n res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON)\n\n return res\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
call_status
python
def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res
Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L291-L316
[ "def _get_devices(params):\n '''\n Parse device(s) ID(s) from the common params.\n\n :param params:\n :return:\n '''\n if 'id' not in params:\n raise CommandExecutionError(\"Parameter ID is required.\")\n\n return type(params['id']) == int and [params['id']] \\\n or [int(dev) for dev in params['id'].split(\",\")]\n", "def _get_lights():\n '''\n Get all available lighting devices.\n '''\n return _query(None, None)\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
call_rename
python
def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="")
Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L319-L341
[ "def _set(lamp_id, state, method=\"state\"):\n '''\n Set state to the device by ID.\n\n :param lamp_id:\n :param state:\n :return:\n '''\n try:\n res = _query(lamp_id, state, action=method, method='PUT')\n except Exception as err:\n raise CommandExecutionError(err)\n\n res = len(res) > 1 and res[-1] or res[0]\n if res.get('success'):\n res = {'result': True}\n elif res.get('error'):\n res = {'result': False,\n 'description': res['error']['description'],\n 'type': res['error']['type']}\n\n return res\n", "def _get_devices(params):\n '''\n Parse device(s) ID(s) from the common params.\n\n :param params:\n :return:\n '''\n if 'id' not in params:\n raise CommandExecutionError(\"Parameter ID is required.\")\n\n return type(params['id']) == int and [params['id']] \\\n or [int(dev) for dev in params['id'].split(\",\")]\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
call_alert
python
def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res
Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L344-L367
[ "def _set(lamp_id, state, method=\"state\"):\n '''\n Set state to the device by ID.\n\n :param lamp_id:\n :param state:\n :return:\n '''\n try:\n res = _query(lamp_id, state, action=method, method='PUT')\n except Exception as err:\n raise CommandExecutionError(err)\n\n res = len(res) > 1 and res[-1] or res[0]\n if res.get('success'):\n res = {'result': True}\n elif res.get('error'):\n res = {'result': False,\n 'description': res['error']['description'],\n 'type': res['error']['type']}\n\n return res\n", "def _get_devices(params):\n '''\n Parse device(s) ID(s) from the common params.\n\n :param params:\n :return:\n '''\n if 'id' not in params:\n raise CommandExecutionError(\"Parameter ID is required.\")\n\n return type(params['id']) == int and [params['id']] \\\n or [int(dev) for dev in params['id'].split(\",\")]\n", "def _get_lights():\n '''\n Get all available lighting devices.\n '''\n return _query(None, None)\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res
saltstack/salt
salt/proxy/philips_hue.py
call_color
python
def call_color(*args, **kwargs): ''' Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5 ''' res = dict() colormap = { 'red': Const.COLOR_RED, 'green': Const.COLOR_GREEN, 'blue': Const.COLOR_BLUE, 'orange': Const.COLOR_ORANGE, 'pink': Const.COLOR_PINK, 'white': Const.COLOR_WHITE, 'yellow': Const.COLOR_YELLOW, 'daylight': Const.COLOR_DAYLIGHT, 'purple': Const.COLOR_PURPLE, } devices = _get_lights() color = kwargs.get("gamut") if color: color = color.split(",") if len(color) == 2: try: color = {"xy": [float(color[0]), float(color[1])]} except Exception as ex: color = None else: color = None if not color: color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE) color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)}) for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, color) return res
Set a color to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **color**: Fixed color. Values are: red, green, blue, orange, pink, white, yellow, daylight, purple. Default white. * **transition**: Transition 0~200. Advanced: * **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation. More: http://www.developers.meethue.com/documentation/hue-xy-values CLI Example: .. code-block:: bash salt '*' hue.color salt '*' hue.color id=1 salt '*' hue.color id=1,2,3 oolor=red transition=30 salt '*' hue.color id=1 gamut=0.3,0.5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L396-L454
[ "def _set(lamp_id, state, method=\"state\"):\n '''\n Set state to the device by ID.\n\n :param lamp_id:\n :param state:\n :return:\n '''\n try:\n res = _query(lamp_id, state, action=method, method='PUT')\n except Exception as err:\n raise CommandExecutionError(err)\n\n res = len(res) > 1 and res[-1] or res[0]\n if res.get('success'):\n res = {'result': True}\n elif res.get('error'):\n res = {'result': False,\n 'description': res['error']['description'],\n 'type': res['error']['type']}\n\n return res\n", "def _get_devices(params):\n '''\n Parse device(s) ID(s) from the common params.\n\n :param params:\n :return:\n '''\n if 'id' not in params:\n raise CommandExecutionError(\"Parameter ID is required.\")\n\n return type(params['id']) == int and [params['id']] \\\n or [int(dev) for dev in params['id'].split(\",\")]\n", "def _get_lights():\n '''\n Get all available lighting devices.\n '''\n return _query(None, None)\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 First create a new user on the Hue bridge by following the `Meet hue <https://www.developers.meethue.com/documentation/getting-started>`_ instructions. To configure the proxy minion: .. code-block:: yaml proxy: proxytype: philips_hue host: [hostname or ip] user: [username] ''' # pylint: disable=import-error,no-name-in-module,redefined-builtin from __future__ import absolute_import, print_function, unicode_literals import salt.ext.six.moves.http_client as http_client # Import python libs import logging import time import salt.utils.json from salt.exceptions import (CommandExecutionError, MinionError) from salt.ext import six __proxyenabled__ = ['philips_hue'] CONFIG = {} log = logging.getLogger(__file__) class Const(object): ''' Constants for the lamp operations. ''' LAMP_ON = {"on": True, "transitiontime": 0} LAMP_OFF = {"on": False, "transitiontime": 0} COLOR_WHITE = {"xy": [0.3227, 0.329]} COLOR_DAYLIGHT = {"xy": [0.3806, 0.3576]} COLOR_RED = {"hue": 0, "sat": 254} COLOR_GREEN = {"hue": 25500, "sat": 254} COLOR_ORANGE = {"hue": 12000, "sat": 254} COLOR_PINK = {"xy": [0.3688, 0.2095]} COLOR_BLUE = {"hue": 46920, "sat": 254} COLOR_YELLOW = {"xy": [0.4432, 0.5154]} COLOR_PURPLE = {"xy": [0.3787, 0.1724]} def __virtual__(): ''' Validate the module. ''' return True def init(cnf): ''' Initialize the module. ''' CONFIG['host'] = cnf.get('proxy', {}).get('host') if not CONFIG['host']: raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if not CONFIG['user']: raise MinionError(message="Cannot find 'user' parameter in the proxy configuration") CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) def ping(*args, **kw): ''' Ping the lamps. ''' # Here blink them return True def shutdown(opts, *args, **kw): ''' Shuts down the service. ''' # This is no-op method, which is required but makes nothing at this point. return True def _query(lamp_id, state, action='', method='GET'): ''' Query the URI :return: ''' # Because salt.utils.query is that dreadful... :( err = None url = "{0}/lights{1}".format(CONFIG['uri'], lamp_id and '/{0}'.format(lamp_id) or '') \ + (action and "/{0}".format(action) or '') conn = http_client.HTTPConnection(CONFIG['host']) if method == 'PUT': conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() if resp.status == http_client.OK: res = salt.utils.json.loads(resp.read()) else: err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) return res def _set(lamp_id, state, method="state"): ''' Set state to the device by ID. :param lamp_id: :param state: :return: ''' try: res = _query(lamp_id, state, action=method, method='PUT') except Exception as err: raise CommandExecutionError(err) res = len(res) > 1 and res[-1] or res[0] if res.get('success'): res = {'result': True} elif res.get('error'): res = {'result': False, 'description': res['error']['description'], 'type': res['error']['type']} return res def _get_devices(params): ''' Parse device(s) ID(s) from the common params. :param params: :return: ''' if 'id' not in params: raise CommandExecutionError("Parameter ID is required.") return type(params['id']) == int and [params['id']] \ or [int(dev) for dev in params['id'].split(",")] def _get_lights(): ''' Get all available lighting devices. ''' return _query(None, None) # Callers def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id=1,2,3 ''' res = dict() lights = _get_lights() for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()): if lights.get(six.text_type(dev_id)): res[dev_id] = lights[six.text_type(dev_id)] return res or False def call_switch(*args, **kwargs): ''' Switch lamp ON/OFF. If no particular state is passed, then lamp will be switched to the opposite state. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: True or False. Inverted current, if omitted CLI Example: .. code-block:: bash salt '*' hue.switch salt '*' hue.switch id=1 salt '*' hue.switch id=1,2,3 on=True ''' out = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): if 'on' in kwargs: state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF else: # Invert the current state state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON out[dev_id] = _set(dev_id, state) return out def call_blink(*args, **kwargs): ''' Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec. CLI Example: .. code-block:: bash salt '*' hue.blink id=1 salt '*' hue.blink id=1,2,3 ''' devices = _get_lights() pause = kwargs.get('pause', 0) res = dict() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): state = devices[six.text_type(dev_id)]['state']['on'] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON) return res def call_ping(*args, **kwargs): ''' Ping the lamps by issuing a short inversion blink to all available devices. CLI Example: .. code-block:: bash salt '*' hue.ping ''' errors = dict() for dev_id, dev_status in call_blink().items(): if not dev_status['result']: errors[dev_id] = False return errors or True def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3 ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): dev_id = six.text_type(dev_id) res[dev_id] = { 'on': devices[dev_id]['state']['on'], 'reachable': devices[dev_id]['state']['reachable'] } return res def call_rename(*args, **kwargs): ''' Rename a device. Options: * **id**: Specifies a device ID. Only one device at a time. * **title**: Title of the device. CLI Example: .. code-block:: bash salt '*' hue.rename id=1 title='WC for cats' ''' dev_id = _get_devices(kwargs) if len(dev_id) > 1: raise CommandExecutionError("Only one device can be renamed at a time") if 'title' not in kwargs: raise CommandExecutionError("Title is missing") return _set(dev_id[0], {"name": kwargs['title']}, method="") def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 salt '*' hue.alert id=1,2,3 on=false ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"}) return res def call_effect(*args, **kwargs): ''' Set an effect to the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **type**: Type of the effect. Possible values are "none" or "colorloop". Default "none". CLI Example: .. code-block:: bash salt '*' hue.effect salt '*' hue.effect id=1 salt '*' hue.effect id=1,2,3 type=colorloop ''' res = dict() devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"effect": kwargs.get("type", "none")}) return res def call_brightness(*args, **kwargs): ''' Set an effect to the lamp. Arguments: * **value**: 0~255 brightness of the lamp. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **transition**: Transition 0~200. Default 0. CLI Example: .. code-block:: bash salt '*' hue.brightness value=100 salt '*' hue.brightness id=1 value=150 salt '*' hue.brightness id=1,2,3 value=255 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' is missing") try: brightness = max(min(int(kwargs['value']), 244), 1) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") try: transition = max(min(int(kwargs['transition']), 200), 0) except Exception as err: transition = 0 devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition}) return res def call_temperature(*args, **kwargs): ''' Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt '*' hue.temperature value=150 id=1 salt '*' hue.temperature value=150 id=1,2,3 ''' res = dict() if 'value' not in kwargs: raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): res[dev_id] = _set(dev_id, {"ct": value}) return res